Search code examples
c#wpfbase64imagesource

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?


Solution

  • I dont think you need the ms.Write line do you? If you do you'll need to set ms.position = 0 after the write. This is because after the write the stream position will be at the end.