[C#參考]BitmapData類
「指定位圖圖像的特性。BitmapData類由Bitmap類的LockBits和UnlockBits方法使用。不可以繼承。(2023-2-25)」
[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;
(ih7K)