您可以通过几种不同的方法来完成。您可以
unsafe用来直接访问数据,也可以使用封送处理来回复制数据。不安全代码更快,但是封送处理不需要不安全代码。这是我前一段时间做的性能比较。
这是一个使用锁位的完整示例:
public unsafe Image ThresholdUA(float thresh){ Bitmap b = new Bitmap(_image);//note this has several overloads, including a path to an image BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat); byte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat); byte* scan0 = (byte*)bData.Scan0.ToPointer(); for (int i = 0; i < bData.Height; ++i) { for (int j = 0; j < bData.Width; ++j) { byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8; //data is a pointer to the first byte of the 3-byte color data //data[0] = blueComponent; //data[1] = greenComponent; //data[2] = redComponent; } } b.UnlockBits(bData); return b;}这是一回事,但需要封送处理:
public Image ThresholdMA(float thresh){ Bitmap b = new Bitmap(_image); BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat); byte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat); int size = bData.Stride * bData.Height; byte[] data = new byte[size]; System.Runtime.InteropServices.Marshal.Copy(bData.Scan0, data, 0, size); for (int i = 0; i < size; i += bitsPerPixel / 8 ) { double magnitude = 1/3d*(data[i] +data[i + 1] +data[i + 2]); //data[i] is the first of 3 bytes of color } System.Runtime.InteropServices.Marshal.Copy(data, 0, bData.Scan0, data.Length); b.UnlockBits(bData); return b;}


