简体   繁体   English

从 URL 加载图像作为 base64 字符串

[英]Load an image from URL as base64 string

I am trying to load an image as a base 64 string so that i can show it in a html like this:我正在尝试将图像加载为 base 64 字符串,以便我可以在这样的 html 中显示它:

 <html><body><img src="data:image/jpeg;base64,/></img></body></html>

Heres my code so far, but it does not really work:到目前为止,这是我的代码,但它并没有真正起作用:

   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();
        }

I tried using this method i found elsewhere to encode the return-String as base64, but when placing it in a html the image just shows the typical placeholder.我尝试使用我在其他地方找到的这种方法将返回字符串编码为 base64,但是当将它放在 html 中时,图像只显示典型的占位符。

    public static string Base64Encode(string plainText)
    {
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return System.Convert.ToBase64String(plainTextBytes);
    }

EDIT:编辑:

Here is how the html looks:这是 html 的外观: 在此处输入图片说明

It seems to me that you need to separate the base64 part, which is only needed in your HTML, from fetching the data from the response.在我看来,您需要将仅在 HTML 中需要的 base64 部分与从响应中获取数据分开。 Just fetch the data from the URL as binary data and convert that to base64.只需从 URL 获取数据作为二进制数据并将其转换为 base64。 Using HttpClient makes this simple:使用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);
    }
}

This assumes the image always will be a JPEG.这是假设的图像永远是一个JPEG。 If it could sometimes be a different content type, you may well want to fetch the response as an HttpResponse and use that to propagate the content type.如果它有时可能是不同的内容类型,您可能希望将响应作为HttpResponse获取并使用它来传播内容类型。

I suspect you may want to add caching here as well :)我怀疑您可能还想在这里添加缓存:)

 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)
                    {
                         
                    }
                }

You must first get the image from disk, then convert it to byte[] and then again to base64.您必须首先从磁盘获取图像,然后将其转换为 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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM