简体   繁体   中英

Bitmap array format in C#

I have following code to create bitmap using array with data*

//Here create the Bitmap to the know height, width and format
Bitmap bmp = new Bitmap( 5,7,PixelFormat.Format1bppIndexed);  
//Create a BitmapData and Lock all pixels to be written 
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),   
ImageLockMode.WriteOnly, bmp.PixelFormat);
//Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(data, 0, bmpData.Scan0, data.Length);     
//Unlock the pixels
bmp.UnlockBits(bmpData);
bmp.Save("BitMapIcon.bmp",ImageFormat.Bmp);

My input array (data ) :

byte[5] data = {0xff,0xff,0xff,0xff,0xff}

Question :

  1. Can array of data* for bitmap input have only valu of each pixel (in this format it is 0 and 1 ) ?
  2. Why passing array of 0xff value some of pixel are not black ?
  3. Can width size be less than 1 byte ?

You have two issues:

  • First, the default palette for the indexed format uses 0 for black and 1 for white. So your code is actually trying to initialize a white bitmap, not a black one

  • Second, and more to the point of your question, is that you are not fully initializing the bitmap. This relates to your third question: the width of the bitmap is allowed to have less than 1 byte's worth of pixels, but the bitmap data itself could require more than that for a single scan line of the bitmap.

Indeed, due to the alignment requirements of a bitmap, your bitmap's "stride" is 4 bytes. So you need 28 bytes total in order to fully initialize the bitmap.

This code will initialize the bitmap the way you want:

//Here create the Bitmap to the know height, width and format
Bitmap bmp = new Bitmap(5, 7, PixelFormat.Format1bppIndexed);
//Create a BitmapData and Lock all pixels to be written 
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
//Copy the data from the byte array into BitmapData.Scan0
byte[] data = new byte[bmpData.Stride * bmpData.Height];

for (int i = 0; i < data.Length; i++)
{
    data[i] = 0xff;
}
Marshal.Copy(data, 0, bmpData.Scan0, data.Length);
//Unlock the pixels
bmp.UnlockBits(bmpData);

Use 0x00 instead of 0xff if you actually wanted black pixels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM