如何从 bmp 文件字节数组创建 BitmapImage?

How to create BitmapImage from a bmp file byte array?

在我的 wpf 应用程序中,我得到了一个 bmp 文件的字节数组。

我想创建一个新的 System.Windows.Media.Imaging.BitmapImage。

我从字节数组创建了 MemoryStream,但它不适用于 SetSource。

有什么建议吗?

添加引用:

using System.IO;

使用以下代码。

MemoryStream ms = new MemoryStream(imageArray);
Image image = Image.FromStream(ms);

对于 WPF

public static BitmapImage GetBitmapImage(byte[] imageArray)
{
    using (var stream = new MemoryStream(imageArray))
    {
        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
        return bitmapImage;
    }
}