位图和位图数据之间的区别



C#中的System.Drawing.bitmapSystem.Drawing.Imaging.bitmapdata之间有什么区别
如何将它们相互转换?

System.Drawing.Bitmap是一个实际的位图对象。您可以使用它来绘制使用从中获得的Graphics实例,您可以在屏幕上显示它,您可以将数据保存到文件中,等等。

System.Drawing.Imaging.BitmapData类是调用Bitmap.LockBits()方法时使用的辅助对象。它包含有关锁定位图的信息,可用于检查位图中的像素数据。

你不能真正在两者之间"转换",因为它们并不代表相同的信息。只需调用LockBits(),就可以Bitmap对象中获得BitmapData对象。如果您有一个来自其他Bitmap对象的BitmapData对象,则可以通过分配一个与原始对象格式相同的对象,在该对象上调用LockBits,然后将字节从一个对象复制到另一个对象,将该数据复制到新的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); 
} 

最新更新