【问题标题】:Create BitMapImage from byte array从字节数组创建 BitMapImage
【发布时间】:2019-09-09 12:05:14
【问题描述】:

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

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 像素的图像,包含两种颜色。

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

提前致谢!

【问题讨论】:

  • 你发明了自己的图像格式; .NET 没有将这种格式解码为位图的编码器。图像格式通常以指示文件格式的“幻数”开头,然后是有关图像的一些元数据,例如其尺寸。由于您的数组是一维的,编码器如何知道这是 10x1 图像,而不是 5x2 图像?所以我猜你想要做的是用原始像素数据初始化一个 BitmapImage 。参见例如stackoverflow.com/questions/1176910/…
  • 您的来源是每像素 8 位。您在任何地方都没有表示您只想使用 256 个可能值中的 2 个。
  • 一个图像文件有一个您缺少的文本标题。如果您使用记事本打开任何二进制图像,您将在文件中看到 ascii 标头。视频卡使用标题来确定图像格式,而您缺少格式。

标签: c# memorystream bitmapimage


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我认为你需要使用 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");
    

    【讨论】:

    • 位图与位图图像不是同一个对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2015-11-19
    • 2013-09-23
    • 2012-04-05
    相关资源
    最近更新 更多