简体   繁体   English

从字节数组创建BitMapImage

[英]Create BitMapImage from byte array

How do I create a bitmapimage object from a byte array. 如何从字节数组创建bitmapimage对象。 Here's my code: 这是我的代码:

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();
}

When running the EndInit() command, I got the following exception. 运行EndInit()命令时,出现以下异常。

No imaging component suitable to complete this operation was found.

I expected that these lines should create an image of dimension 1x10 pixels, containing two colors. 我希望这些行可以创建尺寸为1x10像素的图像,其中包含两种颜色。

What am I doing wrong? 我究竟做错了什么? What does the exception mean? 异常是什么意思?

Thanks in advance! 提前致谢!

When creating a bitmap image the image is loaded from your source based upon its encoding ( BitmapImage and Encoding ). 创建位图图像时,将根据其编码( BitmapImage和Encoding )从源中加载图像。 There are many, many different encodings for bitmaps that are supported by C#. C#支持许多种位图编码

Likely the error you are seeing is because the BitmapImage class is not finding a suitable translation from your byte array to a supported encoding. 您看到的错误可能是因为BitmapImage类找不到从字节数组到支持的编码的合适转换。 (As you can see from the encodings, many are multiples of 4 or 8, which 10 is not). (从编码中可以看到,许多是4或8的倍数,而10则不是)。

I would suggest creating a byte array that contains the correct encoding content for your desired outcome. 我建议创建一个字节数组,其中包含所需结果的正确编码内容。 For example the Rbg24 format would have three bytes worth of data per every pixel. 例如, Rbg24格式每个像素将具有三个字节的数据。

I think you need to use SetPixel() 我认为您需要使用SetPixel()

byte[] data = new byte[10] { 1, 0, 0, 1, 1, 1, 0, 0, 1, 0 };
Bitmap bmp = new Bitmap(1, 10);
for (int i = 0; i < data.Length; i++)
{
  bmp.SetPixel(0, i, data[i] == 1 ? Color.Black : Color.White);
}
bmp.Save("file_path");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM