我正在尝试将图像作为基本64字符串加载,以便我可以在这样的html中显示它:
<html><body><img src="data:image/jpeg;base64,/></img></body></html>
到目前为止,这是我的代码,但它并没有真正起作用:
public async static Task<string> getImage(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "data:image/jpg;charset=base64";
request.Credentials = new NetworkCredential(user, pw);
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
StreamReader sr = new StreamReader(response.GetResponseStream());
return sr.ReadToEnd();
}
我尝试使用我在别处找到的这个方法将return-String编码为base64,但是当将它放在html中时,图像只显示典型的占位符。
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
编辑:
答案 0 :(得分:15)
在我看来,您需要将仅在HTML中需要的base64部分与从响应中获取数据分开。只需从URL获取数据作为二进制数据并将其转换为base64。使用HttpClient
可以很简单:
public async static Task<string> GetImageAsBase64Url(string url)
{
var credentials = new NetworkCredential(user, pw);
using (var handler = new HttpClientHandler { Credentials = credentials })
using (var client = new HttpClient(handler))
{
var bytes = await client.GetByteArrayAsync(url);
return "image/jpeg;base64," + Convert.ToBase64String(bytes);
}
}
这假设图像始终将为JPEG。如果它有时可能是不同的内容类型,您可能希望以HttpResponse
的形式获取响应并使用它来传播内容类型。
我怀疑你可能也想在这里添加缓存:)
答案 1 :(得分:0)
using (HttpClient client = new HttpClient())
{
try
{
using (Stream stream = await client.GetStreamAsync(uri))
{
if (stream == null)
return (Picture)null;
byte[] buffer = new byte[16384];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int num = await stream.ReadAsync(buffer, 0, buffer.Length, cancellation);
int read;
if ((read = num) > 0)
ms.Write(buffer, 0, read);
else
break;
}
imageData = Convert.ToBase64String(ms.ToArray());
}
buffer = (byte[])null;
}
}
catch (Exception ex)
{
}
}
答案 2 :(得分:-1)
您必须首先从磁盘获取映像,然后将其转换为byte [],然后再转换为base64。
public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}