The difference between raster and bitmapdata

What is the difference between System.Drawing.bitmapand System.Drawing.Imaging.bitmapdatain C #?
How to convert them into each other?

+4
source share
2 answers

System.Drawing.Bitmapis the actual raster object. You can use it to draw using the instance Graphicsobtained from it, you can display it on the screen, you can save data to a file, etc.

A class System.Drawing.Imaging.BitmapDatais a helper object used when invoking a method Bitmap.LockBits(). It contains information about a locked bitmap that you can use to check the pixel data in the bitmap.

"" , . BitmapData Bitmap, LockBits(). BitmapData Bitmap, Bitmap, , , LockBits , .

+5

.

Private void LockUnlockBitsExample(PaintEventArgs e) { 
// Create a new bitmap. 
Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
 // Lock the bitmap 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); 
} 
-1

All Articles