这个问题是关于如何读/写,分配和管理位图的像素数据.
下面是一个如何为像素数据分配字节数组(托管内存)并使用它创建位图的示例:
Size size = new Size(800, 600);
PixelFormat pxFormat = PixelFormat.Format8bppIndexed;
//Get the stride, in this case it will have the same length of the width.
//Because the image Pixel format is 1 Byte/pixel.
//Usually stride = "ByterPerPixel"*Width
Run Code Online (Sandbox Code Playgroud)
//但并非总是如此.更多信息在bobpowell.
int stride = GetStride(size.Width, pxFormat);
byte[] data = new byte[stride * size.Height];
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
Bitmap bmp = new Bitmap(size.Width, size.Height, stride,
pxFormat, handle.AddrOfPinnedObject());
//After doing your stuff, free the Bitmap and unpin the array.
bmp.Dispose(); …Run Code Online (Sandbox Code Playgroud)