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:
83 Answers
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 :)
8 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.
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; } } 3
