[C#参考]BitmapData类
「指定位图图像的特性。BitmapData类由Bitmap类的LockBits和UnlockBits方法使用。不可以继承。(2021-1-17)」
[C#参考]BitmapData类
bitmap
指定位图图像的特性。BitmapData类由Bitmap类的LockBits和UnlockBits方法使用。不可以继承。
方法Bitmap.LockBits方法的实现功能是将Bitmap锁定到系统内存中。
使用LockBits方法,可以在系统内存中锁定现有的位图,以便通过编程方式进行修改。尽管用LockBits方式进行大规模更改可以获得更好的性能,但是仍然可以用SetPixel方法来更改图像的颜色。
Bitmap类通过锁定其实例对象的一个矩形的区域返回这个区域的像素数据。所以LockBits函数的返回值的类型是BitmapData,包含选定Bitmap区域的特性。
命名空间:System.Drawing.Image
属性:Height获取或者设置Bitmap对象的像素高度,也成为扫描行数
PixelFormat把Bitmap对象的像素格式信息传递给BitmapData,比如该Bitmap对象每个像素的位深度。
Scan0获取或设置位图中第一个像素数据的地址。
Stride获取或设置Bitmap对象的扫描宽度,以字节为单位。如果跨距为正,则位图自顶向下。 如果跨距为负,则位图颠倒。
Width获取或设置Bitmap对象的像素宽度。也就是一个扫描行中的像素数。
代码实例:
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);
}
利用BitmapData在原图像中扣图
//用指定的大小、像素格式和像素数据初始化 Bitmap 类的新实例。
public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0)
参数
width
类型: System .Int32
新 Bitmap 的宽度(以像素为单位)。
height
类型: System .Int32
新 Bitmap 的高度(以像素为单位)。
stride
类型: System .Int32
指定相邻扫描行开始处之间字节偏移量的整数。这通常(但不一定)是以像素格式表示的字节数(例如,2 表示每像素 16 位)乘以位图的宽度。传递给此参数的值必须为 4 的倍数。
format
类型: System.Drawing.Imaging .PixelFormat
新 Bitmap 的像素格式。 这必须指定以 Format 开头的值。
scan0
类型: System .IntPtr
指向包含像素数据的字节数组的指针。
备注:调用方负责分配和释放 scan0 参数指定的内存块。 但是,直到释放相关的 Bitmap 之后才会释放内存。
代码实现
//获取原始图像的信息
Bitmap srcBmp = new Bitmap("srcImage.png");
Rectangle srcRect = new Rectangle(100, 100, 200, 200);
BitmapData srcBmpData = srcBmp.LockBits(srcRect, ImageLockMode.ReadWrite,srcBmp.PixelFormat);
IntPtr srcPtr = srcBmpData.Scan0;
//生成新的Bitmap对象
Bitmap bm = new Bitmap(100, 100, srcBmpData.Stride, PixelFormat.Format24bppRgb, srcPtr);
//把BitmapData存放到数组里面
int bytes1 = Math.Abs(srcBmpData.Stride) * 100;
byte[] rgbValues1 = new byte[bytes1];
Marshal.Copy(srcPtr, rgbValues1, 0, bytes1);
srcBmp.UnlockBits(srcBmpData);
bm.Save("a.bmp", ImageFormat.Bmp);
pictureBox1.BackgroundImage = bm;
(卖裳)