C# – Reading monochrome bitmap pixel colors

bitmapcdrawinggraphicsnet

I don't know a better title, but I'll describe the problem.

A piece of hardware we use has the ability to display images.
It can display a black and white image with a resolution of 64 x 256.

The problem is the format of the image we have to send to the device.
It is not a standard bitmap format, but instead it is simply an array of
bytes representing each pixel of the image.

0 = black, 1 = white.

So if we had an image with the size: 4 x 4 the byte array might look something like:

1000 0100 0010 0001

And the image would look like:

Bitmap http://www.mediafire.com/imgbnc.php/6ee6a28148d0170708cb10ec7ce6512e4g.jpg

The problem is that we need to create this image by creating a monochrome bitmap
in C# and then convert it to the file format understood by the device.

For example, one might to display text on the device. In order to do so he would
have to create a bitmap and write text to it:

var bitmap = new Bitmap(256, 64);

using (var graphics = Graphics.FromImage(bitmap))
{
    graphics.DrawString("Hello World", new Font("Courier", 10, FontStyle.Regular), new SolidBrush(Color.White), 1, 1);
}

There are 2 problems here:

  1. The generated bitmap isn't monochrome
  2. The generated bitmap has a different binary format

So I need a way to:

  1. Generate a monochrome bitmap in .NET
  2. Read the individual pixel colors for each pixel in the bitmap

I have found that you can set the pixel depth to 16, 24, or 32 bits, but haven't found monochrome and I have no idea how to read the pixel data.

Suggestions are welcome.

UPDATE: I cannot use Win32 PInvokes… has to be platform neutral!

FOLLOW UP: The following code works for me now. (Just in case anybody needs it)

private static byte[] GetLedBytes(Bitmap bitmap)
{
    int threshold = 127;
    int index = 0;
    int dimensions = bitmap.Height * bitmap.Width;

    BitArray bits = new BitArray(dimensions);

    //Vertically
    for (int y = 0; y < bitmap.Height; y++)
    {
        //Horizontally
        for (int x = 0; x < bitmap.Width; x++)
        {
            Color c = bitmap.GetPixel(x, y);
            int luminance = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
            bits[index] = (luminance > threshold);
            index++;
        }
    }

    byte[] data = new byte[dimensions / 8];
    bits.CopyTo(data, 0);
    return data;
}

Best Answer

I'd compute the luminance of each pixel a then compare it to some threshold value.

y=0.3*R+0.59G*G+0.11*B

Say the threshold value is 127:

const int threshold = 127;
Bitmap bm = { some source bitmap };

byte[,] buffer = new byte[64,256];

for(int y=0;y<bm.Height;y++)
{
  for(int x=0;x<bm.Width;x++)
  {
   Color c=source.GetPixel(x,y);
   int luminance = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11);
   buffer[x,y] = (luminance  > 127) ? 1 : 0;
  }
}