C#的Bitmap.LockBits 使用说明

 
翻译
英语

转自:Bitmap.LockBits 方法 (Rectangle, ImageLockMode, PixelFormat)


将 Bitmap 锁定到系统内存中。(16.6.15Useful)

命名空间:    System.Drawing
程序集:  System.Drawing(System.Drawing.dll 中)

[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public BitmapData LockBits(
	Rectangle rect,
	ImageLockMode flags,
	PixelFormat format
)
参数
rect

Rectangle 结构,它指定要锁定的 Bitmap 部分。

flags

ImageLockMode 枚举,它指定 Bitmap 的访问级别(读/写)。

format

PixelFormat 枚举,它指定此 Bitmap 的数据格式。

返回值
Type:  System.Drawing.Imaging.BitmapData

BitmapData,它包含有关此锁定操作的信息。

Exception Condition
ArgumentException

PixelFormat 不是特定的每像素位数值。

- 或 -

为位图传入了错误的 PixelFormat

Exception

操作失败。

使用 LockBits 方法,可在系统内存中锁定现有的位图,以便通过编程方式进行更改。尽管用 LockBits 方法进行大规模更改可获得更好的性能,但仍然可以用 SetPixel 方法来更改图像的颜色。

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

调用此方法时,应使用包含特定的每像素位数 (BPP) 值的 System.Drawing.Imaging.PixelFormat 枚举的成员。使用 System.Drawing.Imaging.PixelFormat 值(如 Indexed 和 Gdi)会引发 System.ArgumentException同样,为位图传递不正确的像素格式也会引发 System.ArgumentException

下面的代码示例演示如何使用 PixelFormatHeightWidth 和 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);

        
}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值