C# Base64 String to JPEG Image

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

I am trying to convert a Base64String to an image which needs to be saved locally.

At the moment, my code is able to save the image but when I open the saved image, it says "Invalid Image".

Code:

try {     using (var imageFile = new StreamWriter(filePath))     {         imageFile.Write(resizeImage.Content);         imageFile.Close();     } } 

The Content is a string object which contains the Base64 String.

回答1:

So with the code you have provided.

var bytes = Convert.FromBase64String(resizeImage.Content); using (var imageFile = new FileStream(filePath, FileMode.Create)) {     imageFile.Write(bytes ,0, bytes.Length);     imageFile.Flush(); } 


回答2:

First, convert the base 64 string to an Image, then use the Image.Save method.

To convert from base 64 string to Image:

 public Image Base64ToImage(string base64String)  {     // Convert base 64 string to byte[]     byte[] imageBytes = Convert.FromBase64String(base64String);     // Convert byte[] to Image     using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))     {         Image image = Image.FromStream(ms, true);         return image;     }  } 

To convert from Image to base 64 string:

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 base 64 string     string base64String = Convert.ToBase64String(imageBytes);     return base64String;   } } 

Finally, you can easily to call Image.Save(filePath); to save the image.



回答3:

public Image Base64ToImage(string base64String) {    // Convert Base64 String to byte[]     byte[] imageBytes = Convert.FromBase64String(base64String);     MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);      // Convert byte[] to Image     ms.Write(imageBytes, 0, imageBytes.Length);     Image image = Image.FromStream(ms, true);      return image; } 


回答4:

Front :

  

Back:

 public async void Base64ToImage(string base64String)         {             // read stream             var bytes = Convert.FromBase64String(base64String);             var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();              // decode image             var decoder = await BitmapDecoder.CreateAsync(image);             image.Seek(0);              // create bitmap             var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);             await output.SetSourceAsync(image);              camImage.Source = output;         } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!