C#的Bitmap.LockBits 使用说明

来源:互联网 发布:js获取当前时间加一年 编辑:程序博客网 时间:2024/05/17 03:11
 
翻译
英语

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


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

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

语法

C#
C++
F#
VB
[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,它包含有关此锁定操作的信息。

异常

ExceptionConditionArgumentException

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 传递。

C#
C++
VB
    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);        }

0 0
原创粉丝点击