首页 > 解决方案 > 从字节数组创建 BitMapImage

问题描述

如何从字节数组创建位图图像对象。这是我的代码:

System.Windows.Media.Imaging.BitmapImage image = new 
System.Windows.Media.Imaging.BitmapImage();
byte[] data = new byte[10] { 1, 0, 0, 1, 1, 1, 0, 0, 1, 0 };
using (var ms = new System.IO.MemoryStream(data))
{
    image.BeginInit();
    image.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
    image.StreamSource = ms;
    image.EndInit();
}

运行 EndInit() 命令时,出现以下异常。

No imaging component suitable to complete this operation was found.

我希望这些线条应该创建一个尺寸为 1x10 像素的图像,包含两种颜色。

我究竟做错了什么?异常是什么意思?

提前致谢!

标签: c#memorystreambitmapimage

解决方案


创建位图图像时,图像是根据其编码(BitmapImage 和 Encoding)从您的源加载的。C# 支持的位图 有很多很多不同的编码。

您看到的错误可能是因为 BitmapImage 类没有找到从您的字节数组到支持的编码的合适转换。(从编码中可以看出,许多是 4 或 8 的倍数,而 10 不是)。

我建议创建一个字节数组,其中包含您想要的结果的正确编码内容。例如,Rbg24格式的每个像素将具有三个字节的数据。


推荐阅读