alignment - Parse/Read Bitmap file in C -
i'm trying make program read data bitmap file (.bmp, windows file format, 8bit). right i'm stuck on reading headers before image data.
i used specifications bmp found here make these structs hold file header, info header, , image data of bmp:
typedef struct { unsigned char filemarker1; unsigned char filemarker2; unsigned int bfsize; uint16_t unused1; uint16_t unused2; unsigned int imagedataoffset; } fileheader; typedef struct { unsigned int bisize; int width; int height; uint16_t planes; uint16_t bitpix; unsigned int bicompression; unsigned int bisizeimage; int bixpelspermeter; int biypelspermeter; unsigned int biclrused; unsigned int biclrimportant; } infoheader; typedef struct { unsigned char b; unsigned char g; unsigned char r; } image;
i can't see wrong these (unless source specification wrong, i've looked elsewhere , seems me ok).
i'm using following code test gets parsed correctly:
int main(void) { fileheader fh; infoheader ih; file *img = fopen("img.bmp", "rb"); fread(&fh, sizeof(unsigned char), sizeof(fileheader), img); fread(&ih, sizeof(unsigned char), sizeof(infoheader), img); printf("fm1 = %c, fm2 = %c, bfs = %u, un1 = %hu, un2 = %hu, ido = %u\n", fh.filemarker1, fh.filemarker2, fh.bfsize, fh.unused1, fh.unused2, fh.imagedataoffset); printf("w = %d, h = %d\n", ih.width, ih.height); return 0; }
unfortunately when run wrong result:
user$ ./images fm1 = b, fm2 = m, bfs = 0, un1 = 0, un2 = 118, ido = 2621440 w = 3276800, h = 65536
according link, unused1 , 2 should 0. also, width , height wrong (it's 16x16 image).
it seems there sort of alignment issue going on structures. have experience this? (i don't want use image/bitmap libraries, want myself).
thanks help!
yup forgot pack structs. fixes things. oops:
typedef struct __attribute__((__packed__)) { unsigned char filemarker1; unsigned char filemarker2; unsigned int bfsize; uint16_t unused1; uint16_t unused2; unsigned int imagedataoffset; } fileheader; typedef struct __attribute__((__packed__)) { unsigned int bisize; int width; int height; uint16_t planes; uint16_t bitpix; unsigned int bicompression; unsigned int bisizeimage; int bixpelspermeter; int biypelspermeter; unsigned int biclrused; unsigned int biclrimportant; } infoheader; typedef struct __attribute__((__packed__)) { unsigned char b; unsigned char g; unsigned char r; } image;
Comments
Post a Comment