字节数组或矩阵转换为位图

7

我目前遇到的问题是:我想将从具有以下配置的文件中获取的字节数组转换为:

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逐个设置像素,因为这需要太长时间。 有什么建议吗?提前致谢!

如果你只有一个字节数组,那么如何确定它的宽度/高度?它是一个二维数组吗?还是提前给定的? - vcsjones
你看过这个吗?https://dev59.com/-2w15IYBdhLWcg3wLIo2 Bitmap类有一个构造函数可以直接使用字节数组:http://msdn.microsoft.com/en-us/library/zy1a2d14 - kol
是的,我有图像的宽度和高度。在这种情况下,它是1280 x 720。 - waclock
是的Kol,我看到了那些。我尝试使用(MemoryStream stream = new MemoryStream(ArregloBytes)) { Bitmap bmp = new Bitmap(stream); frames.Enqueue(bmp); } - waclock
但是我收到了一个异常,说参数无效。 - waclock
1个回答

11

如果你已经有了像素的 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都无法识别。我需要哪些额外的库? - waclock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接