Question

I'm trying to read pixel data from a bitmap into an array of structured (which contains R, G and B ints, for the colours). I'm using a 12x12px image just for testing (because I believe that the bmp specification says that pixel data is padded with zeros at the end of each line to make it word-aligned. 12px width is automatically word aligned.

Here is the code I'm using. the INFOHEADER and FILEHEADER are parsed perfectly, and a 12x12 2D array of IMAGEs im is created. However printing the RGB data for each pixel prints rubbish.

typedef struct __attribute__((__packed__)) {
    unsigned char  b;
    unsigned char  g;
    unsigned char  r;
} IMAGE;

int main(void) {
    FILEHEADER fh;
    INFOHEADER ih;
    FILE *img = fopen("pic.bmp", "rb");
    fread(&fh, sizeof(unsigned char), sizeof(FILEHEADER), img);
    fread(&ih, sizeof(unsigned char), sizeof(INFOHEADER), img);

    IMAGE im[ih.width][ih.height];
    fseek(img, fh.imageDataOffset, 0);
    int i, j;
    for (i = ih.height-1; i >= 0; i--) {
        for (j = 0; j < ih.width; j++) {
            fread(&im[i][j], sizeof(unsigned char), sizeof(IMAGE), img);
            printf("%x%x%x ", im[i][j].r, im[i][j].g, im[i][j].b);
        }
        printf("\n");
    }
    printf("w = %d, h = %d\n", ih.width, ih.height);
}

However, for a 12x12px completely white bitmap, this outputs:

ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff 
ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff 
ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff 
ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff ffffff 
000 ca800 ff574b 007f 001 000 b000 574bc9 07fff 44c40 ff8690 007f 
9077b0 7fff86 8000 574bca 07fff 0a00 ff7482 007f 4bc950 7fff57 2f00 86906d 
07fff 60a50 ff8690 007f 4bc9d0 7fff57 ee00 87418 000 c9300 ff574b 007f 
4bc8f0 7fff57 700 868b3c 07fff 400 000 000 820a0 7fff74 3000 574bc9 
07fff 6000 1877 000 0100 000 000 004 000 1000 000 000 
820a0 7fff74 000 0010 000 6000 1874 000 4bc8d0 7fff57 b300 868b31 
000 38b30 051f9 000 000 000 000 000 000 010 000 000 
745069 018 f700 ffffff 181a4 080 000 000 01f5 0140 000 000 

Can anyone see what I'm doing wrong? Could it be an alignment issue?

Thanks

EDIT:

This is a screenshot of the bottom of the bitmap file. There seems to be 144 (12x12) white pixels (highlighted). The last two zeros are padding. It still doesn't make sense that my program doesn't parse this properly though.

enter image description here

Was it helpful?

Solution

Ok it turns out that I saved my blank bmp as 8bit instead of 24bit. 8bit uses a colour table, and each pixel references an entry in the colour table to get its data. 24bit bmp uses 3 bytes per pixel, and each byte represents an R, G and B value, so it doesn't need a colour table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top