Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 image to WPF image source error No imaging component suitable

I am trying to decode a Base64 image and place it into a WPF image source. However, the code I am using has an error of:

No imaging component suitable to complete this operation was found.

error

I have double-checked that the Base64 string I have is, in fact, a correct Base64 encoding by using an online Base64 Decoder so I know its not that.

My code:

byte[] binaryData = Convert.FromBase64String(desc.Icon_Path);
MemoryStream ms = new MemoryStream(binaryData, 0, binaryData.Length);
ms.Write(binaryData, 0, binaryData.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
icon.Source = ToWpfImage(image);
ms.Dispose();

public BitmapImage ToWpfImage(System.Drawing.Image img)
{
  MemoryStream ms = new MemoryStream();
  img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

  BitmapImage ix = new BitmapImage();
  ix.BeginInit();
  ix.CacheOption = BitmapCacheOption.OnLoad;
  ix.StreamSource = ms;
  ix.EndInit();
  return ix;
}

What could I be doing incorrect?

like image 809
StealthRT Avatar asked Jan 20 '26 17:01

StealthRT


1 Answers

Given that the Base64 string contains an encoded image buffer that can be decoded by one of WPF's BitmapDecoders, you do not need more code than this:

public static BitmapSource BitmapFromBase64(string b64string)
{
    var bytes = Convert.FromBase64String(b64string);

    using (var stream = new MemoryStream(bytes))
    {
        return BitmapFrame.Create(stream,
            BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    }
}
like image 161
Clemens Avatar answered Jan 22 '26 08:01

Clemens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!