3

I receive a image/jpeg;base64 string from server. How can I convert this string to BitmapImage and set like Image.Source ?

string imgStr = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAQABAAD .... ";
BitmapImage bmp = Base64StringToBitmap(imgStr);
myImage.Source = bmp;

Thanks in advance!

el-niko
  • 113
  • 1
  • 10

1 Answers1

6

I find solution for my issue:

public static BitmapImage Base64StringToBitmap(string  base64String)
{
    byte[] byteBuffer = Convert.FromBase64String(base64String);
    MemoryStream memoryStream = new MemoryStream(byteBuffer);
    memoryStream.Position = 0;

    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.SetSource(memoryStream);

    memoryStream.Close();
    memoryStream = null;
    byteBuffer = null;

    return bitmapImage;
}
Cute Bear
  • 3,223
  • 13
  • 44
  • 69
el-niko
  • 113
  • 1
  • 10
  • I don't know if things changed in .Net 6 or what but for me this solution did not work. After various tests I was able to get it working by: 1. not closing the memoryStream, so removed the line `memoryStream.Close();`, and 2. calling the `BitmapImage.BeginInit()` before the line `bitmapImage.SetSource(memoryStream);`, similarly 3. calling the `BitmapImage.EndInit()` after the line `bitmapImage.SetSource(memoryStream);`. I've confirmed all three are required to work in my case. – notarobot Mar 18 '23 at 20:31