1#
Convert Image to Base64 String and Base64 String to Image
http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx

This article will help you to learn how we can convert an image into a base64 string and base64 string back to image.

Image to Base64 String
  1. public string ImageToBase64(Image image,
  2.   System.Drawing.Imaging.ImageFormat format)
  3. {
  4.   using (MemoryStream ms = new MemoryStream())
  5.   {
  6.     // Convert Image to byte[]
  7.     image.Save(ms, format);
  8.     byte[] imageBytes = ms.ToArray();

  9.     // Convert byte[] to Base64 String
  10.     string base64String = Convert.ToBase64String(imageBytes);
  11.     return base64String;
  12.   }
  13. }
复制代码
Base64 String to Image
  1. public Image Base64ToImage(string base64String)
  2. {
  3.   // Convert Base64 String to byte[]
  4.   byte[] imageBytes = Convert.FromBase64String(base64String);
  5.   MemoryStream ms = new MemoryStream(imageBytes, 0,
  6.     imageBytes.Length);

  7.   // Convert byte[] to Image
  8.   ms.Write(imageBytes, 0, imageBytes.Length);
  9.   Image image = Image.FromStream(ms, true);
  10.   return image;
  11. }
复制代码
解决问题的代码:
  1. String url = "http://ecx.images-amazon.com/images/I/51MVXV3QQ6L._SL500_SS150_.jpg";

  2. Uri uri = new Uri(url);

  3. WebClient client = new WebClient();
  4. byte[] imageBytes = client.DownloadData(uri);

  5. string base64String = Convert.ToBase64String(imageBytes);

  6. base64String.Dump();

  7. base64String.Length.Dump();
  8. ("<img src='data:image/jpg;base64," + "' />").Length.Dump();

  9. client.Dispose();
复制代码