C# Using BinaryReader to read color byte values of a bitmap image

1.6k views Asked by At

I am using BinaryReader to read the bytes of an image, I am having some issues trying to read the ARGB values of a bitmap image using BinaryReader. Can anyone suggest a way I could get the byte value for each pixel in a bitmap image?

Thanks in advance

3

There are 3 answers

0
Bart Juriewicz On BEST ANSWER

Easy way is to use unsafe context and lock some bits. Oversimplified sample:

unsafe
{
    var bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);

    byte* first = (byte*)bitmapData.Scan0;   
    byte a = first[0];
    byte r = first[1];
    byte g = first[2];
    byte b = first[3];

    ...

    bmp.UnlockBits(bitmapData);
}

However, if you still need to use BinaryReader and you know how many bytes per pixel there are, It is possible to just skip the header (you can find it's length in @Bradley_Ufffner 's link) and access the bytes.

0
IS4 On

If you need to read a bitmap's pixel data using BinaryReader, try UnmanagedMemoryStream:

Bitmap bmp = new Bitmap("img.bmp");
var bits = bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
try{
    unsafe{
        using(Stream bmpstream = new UnmanagedMemoryStream((byte*)bits.Scan0, bits.Height*bits.Stride))
        {
            BinaryReader reader = new BinaryReader(bmpstream);
            for(int y = 0; y < bits.Height; y++)
            {
                bmpstream.Seek(bits.Stride*y, SeekOrigin.Begin);
                for(int x = 0; x < bits.Width; x++)
                {
                    byte b = reader.ReadByte();
                    byte g = reader.ReadByte();
                    byte r = reader.ReadByte();
                    byte a = reader.ReadByte();
                }
            }
        }
    }
}finally{
    bmp.UnlockBits(bits);
}
0
Bradley Uffner On

You will need to study the BMP file format available here: http://en.wikipedia.org/wiki/BMP_file_format Reading the file correctly will involve figuring out the pixel format from the header and parsing the data correctly based on that. The file may be palatalized, in which case you will need to read out the color table data and use it to map pixels to actual colors. Pixel data may also be compressed and will have to be extracted based on values in the header.

This won't be a simple project, things like this are the reason graphics libraries were invented.