Base64 图像转 WPF 图像源错误 没有合适的图像组件

Ste*_*hRT 3 c# wpf base64 imagesource

我正在尝试解码 Base64 图像并将其放入 WPF 图像源中。但是,我使用的代码有一个错误:

没有找到适合完成此操作的成像组件。

错误

我已经使用在线 Base64 解码器仔细检查了我拥有的 Base64 字符串是否是正确的 Base64 编码,所以我知道它不是。

我的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我可能做错了什么?

Cle*_*ens 5

鉴于 Base64 字符串包含可以由 WPF 的BitmapDecoders之一解码的编码图像缓冲区,您不需要比这更多的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)