c# – 如何将图像(.png)转换为base64字符串,反之亦然,并将其转换为指定位置

前端之家收集整理的这篇文章主要介绍了c# – 如何将图像(.png)转换为base64字符串,反之亦然,并将其转换为指定位置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将图像(png)存储到 Windows 8应用程序中的sqlite数据库,我发现它可以通过将其转换为base64字符串并将字符串存储到数据库来完成.稍后在应用程序中我想将该base64字符串转换为png图像并将其存储到指定位置.问题是我不知道如何将图像转换为base64和base64图像并将其存储到c#windows 8 app中的指定位置.任何帮助,将不胜感激.

解决方法

  1. public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
  2. {
  3. using (MemoryStream ms = new MemoryStream())
  4. {
  5. // Convert Image to byte[]
  6. image.Save(ms,format);
  7. byte[] imageBytes = ms.ToArray();
  8.  
  9. // Convert byte[] to Base64 String
  10. string base64String = Convert.ToBase64String(imageBytes);
  11. return base64String;
  12. }
  13. }
  14.  
  15.  
  16.  
  17. public Image Base64ToImage(string base64String)
  18. {
  19. // Convert Base64 String to byte[]
  20. byte[] imageBytes = Convert.FromBase64String(base64String);
  21. using (var ms = new MemoryStream(imageBytes,imageBytes.Length))
  22. {
  23.  
  24. // Convert byte[] to Image
  25. ms.Write(imageBytes,imageBytes.Length);
  26. Image image = Image.FromStream(ms,true);
  27. return image;
  28. }
  29. }

猜你在找的C#相关文章