[英]Difference between bitmap and bitmapdata
C#中的System.Drawing.bitmap
和System.Drawing.Imaging.bitmapdata
什么區別?
如何將它們互相轉換?
System.Drawing.Bitmap
是一個實際的位圖對象。 您可以使用它來繪制使用從它獲得的Graphics
實例,您可以在屏幕上顯示它,您可以將數據保存到文件等。
System.Drawing.Imaging.BitmapData
類是調用Bitmap.LockBits()
方法時使用的輔助對象。 它包含有關鎖定位圖的信息,您可以使用它來檢查位圖中的像素數據。
你不能真正在兩者之間“轉換”,因為它們不代表相同的信息。 只需調用LockBits()
即可從Bitmap
對象獲取 BitmapData
對象。 如果你有一個BitmapData
從其他對象Bitmap
對象,就可以將數據復制到一個新Bitmap
對象被分配一個具有相同的格式原來,呼吁LockBits
上一個一樣,那么僅僅復制字節從一個到其他。
將位圖轉換為位圖數據。 另請參閱此鏈接
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.