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:

 <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.

    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: enter image description here

Jon Skeet
people
quotationmark

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. Just fetch the data from the URL as binary data and convert that to base64. Using HttpClient makes this simple:

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. 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.

I suspect you may want to add caching here as well :)

people

See more on this question at Stackoverflow