【问题标题】:Byte array or matrix to BitMap字节数组或矩阵到 BitMap
【发布时间】:2012-06-11 14:59:02
【问题描述】:

我目前遇到以下问题:我想转换来自具有以下配置的文件的字节数组:

Byte1: R color of pixel 0,0.
Byte2: G color of pixel 0,0.
Byte3: B color of pixel 0,0.
Byte4: R color of pixel 0,1.

...
ByteN: R color of pixel n,n.

所以我想做的是将这些字节转换为位图,而不必使用bitmap.setPixel 逐像素设置,因为它需要太长时间。

有什么建议吗?提前致谢!

【问题讨论】:

  • 如果你只有一个字节数组,你如何确定宽度/高度?是二维数组吗?是事先给你的吗?
  • 你见过这个吗? stackoverflow.com/questions/6782489/… Bitmap 类有一个直接使用字节数组的ctor:msdn.microsoft.com/en-us/library/zy1a2d14
  • 是的,我确实有图像的宽度和高度。在本例中为 1280 x 720。
  • 是的,Kol 我看到了,我尝试使用 (MemoryStream stream = new MemoryStream(ArregloBytes)) { Bitmap bmp = new Bitmap(stream); frames.Enqueue(bmp); }
  • 但是我得到一个异常说这个参数是无效的。

标签: c# arrays bitmap byte


【解决方案1】:

如果您有像素的byte[] 以及宽度和高度,那么您可以使用BitmapData 将字节写入位图,因为您也知道格式。这是一个例子:

//Your actual bytes
byte[] bytes = {255, 0, 0, 0, 0, 255};
var width = 2;
var height = 1;
//Make sure to clean up resources
var bitmap = new Bitmap(width, height);
var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
bitmap.UnlockBits(data);

这是一个非常快的操作。

您至少需要在 C# 文件的顶部导入这三个命名空间:

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

【讨论】:

  • 感谢您的回复,我尝试使用您的代码,但无法识别 ImageLockMode、PixelFormat 和 Marshal。我需要哪些额外的库?
猜你喜欢
  • 2016-07-31
  • 2021-03-13
  • 1970-01-01
  • 2016-05-18
  • 2012-02-18
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多