我有一个类似于byte[] pixels
的数组。有什么方法可以在不复制数据的情况下从 pixels
创建 bitmap
对象?我有一个小型图形库,当我需要在 WinForms
窗口上显示图像时,我只是将该数据复制到一个 bitmap
对象,然后我使用 draw 方法。我可以避免这个复制过程吗?我记得我在哪里见过它,但也许我记性不好。
编辑:我试过这段代码并且它有效,但这安全吗?
byte[] pixels = new byte[10 * 10 * 4];
pixels[4] = 255; // set 1 pixel
pixels[5] = 255;
pixels[6] = 255;
pixels[7] = 255;
// do some tricks
GCHandle pinnedArray = GCHandle.Alloc(pixels, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// create a new bitmap.
Bitmap bmp = new Bitmap (10, 10, 4*10, PixelFormat.Format32bppRgb, pointer);
Graphics grp = this.CreateGraphics ();
grp.DrawImage (bmp, 0, 0);
pixels[4+12] = 255; // add a pixel
pixels[5+12] = 255;
pixels[6+12] = 255;
pixels[7+12] = 255;
grp.DrawImage (bmp, 0, 40);
最佳答案
有一个构造函数接受指向原始图像数据的指针:
Bitmap Constructor (Int32, Int32, Int32, PixelFormat, IntPtr)
例子:
byte[] _data = new byte[]
{
255, 0, 0, 255, // Blue
0, 255, 0, 255, // Green
0, 0, 255, 255, // Red
0, 0, 0, 255, // Black
};
var arrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(_data,
System.Runtime.InteropServices.GCHandleType.Pinned);
var bmp = new Bitmap(2, 2, // 2x2 pixels
8, // RGB32 => 8 bytes stride
System.Drawing.Imaging.PixelFormat.Format32bppArgb,
arrayHandle.AddrOfPinnedObject()
);
this.BackgroundImageLayout = ImageLayout.Stretch;
this.BackgroundImage = bmp;
关于c# - 从数组创建位图对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989567/