你會使用Lockbits
和Marshal.Copy
:
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
// do something with the array
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
bmp.UnlockBits(bmpData);
注:該代碼基本上是從LockBits
文檔頁面的示例代碼,但是代碼有一個限制。它假設Stride
值爲正數,即圖像沒有上下顛倒存儲在內存中,儘管在Stride
值上使用Math.Abs
表示編寫代碼的人知道Stride
值可能是負值。
對於負值Stride
值,Scan0
不能用作連續存儲器塊的起始地址,因爲它是第一條掃描線的地址。內存塊的起始地址將是圖像中最後一行的起始地址,而不是第一個地址。
該地址將是bmpData.Scan0 + bmpData.Stride * (bmp.Height - 1)