Subby Subby - 29 days ago 16
C# Question

C# Base64 String to JPEG Image

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

enter image description here

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.

Answer

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();
}