Christopher Janzon
Christopher Janzon

Reputation: 1039

BMP file format not read properly?

Hey folks!

I got this image.bmp. When i read it with all padding included and such i get this result.

What am i doing wrong here besides reading the image upside down? I don't find anything relative on Wikipedia or by googling. It seems that after 24 pixels width the image is mirrored 8 pixels. Why!? I don't get it!? How can i fix this!?

I'm reading the file with some C++ code on Windows reading the BMP file raw. The image file is monochrome. 1 bit per pixel.

Code for showing bitmap data:

unsigned int count = 0; // Bit counting variable
unsigned char *bitmap_data = new char[size]; // Array containing the raw data of the image

for(unsigned int i=0; i<size; i++){ // This for-loop goes through every byte of the bitmap_data

    for(int j=1; j<256; j*=2){ // This gives j 1, 2, 4, 8, 16, 32, 64 and 128. Used to go through every bit in the bitmap_data byte

        if(count >= width){ // Checking if the row is ended
            cout << "\n"; // Line feed

            while(count > 32) count -=32; // For padding.
            if(count < 24) i++;
            if(count < 16) i++;
            if(count < 8) i++;

            count = 0; // resetting bit count and break out to next row
            break;
        }

        if(i>=size) break; // Just in case

        count++; // Increment the bitcounter. Need to be after end of row check

        if(bitmap_data[i] & j){ // Compare bits
            cout << (char)0xDB; // Block
        }else{
            cout << (char)' ';  // Space
        }
    }
}

Thanks in advance!

Upvotes: 2

Views: 1779

Answers (1)

JasonD
JasonD

Reputation: 16582

You are almost certainly interpreting/outputting the bits in the wrong order in each byte. This results in each column of 8 pixels being flipped left to right.

The BMP format states that the left-most pixel is the most significant bit, and the right-most pixel is the least. In your code, you are iterating the wrong way through the bits.

Upvotes: 4

Related Questions