-1

Possible Duplicate:
Convert a image to a monochrome byte array

I have a monochrome bitmap image. I load the image like this:

Image image = Image.FromFile("myMonoChromeImage.bmp");

How can I get a binary array, where 1s represent white pixels and 0s represent black pixels, or vice versa? (The first bit in the array is the top-left pixel and the last bit in array is the bottom-right pixel)

If possible, an efficient approach would be appreciated.

Community
  • 1
  • 1
Ribel Fares
  • 11
  • 1
  • 2
  • @Panagiotis Kanavos The mentioned question is for a byte array. I'm sorry but I do not know what each byte represent in a monochrome bitmap (8 pixels?). – Ribel Fares Jun 12 '12 at 09:12
  • 1
    this is the question/answer you're looking for: http://stackoverflow.com/questions/2593768/convert-a-image-to-a-monochrome-byte-array. – Nadir Sampaoli Jun 12 '12 at 09:25

1 Answers1

0

You can use LockBits to get access to the bitmap data and copy the values directly from the bitmap array. GetPixel essentially locks and unlocks the bitmap each time so it's not efficient.

You can extract the data to a byte array and then check the RGBA values to see if they are white (255,255,255,255) or black (0,0,0,255)

The BitmapData class sample shows how to do this. In your case the code would be something like this:

        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, 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);

        // Unlock the bits.
        bmp.UnlockBits(bmpData);
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • How to convert it back to bitmap using the byte array, pixel format information , width and height only? – Manish Dubey Sep 24 '15 at 08:04
  • If you want to ask a new question, you should do just that. Almost no-one notices comments to old questions. It's also impossible to give a proper answer, post code or examples in a comment – Panagiotis Kanavos Sep 24 '15 at 10:14
  • Besides, there's no need to convert anything. BitmapData operates on a specific bitmap's data. Once you unlock it, the bitmaps can be used. This is also shown in the linked example. I suspect you want to ask a completely different question, ie how to create a bitmap from raw bytes? – Panagiotis Kanavos Sep 24 '15 at 10:17