翻译
英语
|
转自:Bitmap.LockBits 方法 (Rectangle, ImageLockMode, PixelFormat)
将 Bitmap 锁定到系统内存中。(16.6.15Useful)
程序集: System.Drawing(System.Drawing.dll 中)
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public BitmapData LockBits(
Rectangle rect,
ImageLockMode flags,
PixelFormat format
)
Exception | Condition |
---|---|
ArgumentException | |
Exception |
操作失败。 |
使用 LockBits 方法,可在系统内存中锁定现有的位图,以便通过编程方式进行更改。尽管用 LockBits 方法进行大规模更改可获得更好的性能,但仍然可以用 SetPixel 方法来更改图像的颜色。
BitmapData 指定 Bitmap 的特性,如大小、像素格式、像素数据在内存中的起始地址以及每个扫描行的长度(步幅)。
调用此方法时,应使用包含特定的每像素位数 (BPP) 值的 System.Drawing.Imaging.PixelFormat 枚举的成员。使用 System.Drawing.Imaging.PixelFormat 值(如 Indexed 和 Gdi)会引发 System.ArgumentException。同样,为位图传递不正确的像素格式也会引发 System.ArgumentException。
下面的代码示例演示如何使用 PixelFormat、Height、Width 和 Scan0 属性;LockBits 和 UnlockBits 方法;以及 ImageLockMode 枚举。此示例是针对使用 Windows 窗体而设计的。此示例不是设计用于像素格式,只是提供一个例子表明如何使用 LockBits 方法。若要运行此示例,请将其粘贴到一个窗体中,然后通过调用 LockUnlockBitsExample 方法处理该窗体的 Paint 事件,并将 e 作为 PaintEventArgs 传递。
private void LockUnlockBitsExample(PaintEventArgs e) { // Create a new bitmap. Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg"); // Lock the bitmap's bits. 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); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. 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); // Set every third value to 255. A 24bpp bitmap will look red. for (int counter = 2; counter < rgbValues.Length; counter += 3) rgbValues[counter] = 255; // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); // Draw the modified image. e.Graphics.DrawImage(bmp, 0, 150); }