Bitmap.UnlockBits(BitmapData) 方法

定义

从系统内存解锁此 Bitmap

public void UnlockBits (System.Drawing.Imaging.BitmapData bitmapdata);

参数

bitmapdata
BitmapData

一个 BitmapData,指定有关锁定操作的信息。

例外

此操作失败。

示例

下面的代码示例演示如何使用 、、 和 属性、LockBitsUnlockBits 方法以及 ImageLockMode 枚举。Scan0WidthHeightPixelFormat 此示例并非旨在正确处理所有像素格式,而是提供如何使用 LockBits 方法的示例。 此示例旨在与 Windows 窗体 一起使用。 若要运行此示例,请将其粘贴到窗体中,并通过调用 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);
    }

注解

指定 BitmapDataBitmap的属性,例如大小、像素格式、内存中像素数据的起始地址以及每个扫描行 (步幅) 的长度。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9