Reading BMP headers, packed. Reading incorrect values
I've recently made a program to read the fileheader and infoheader of a BMP file. I packed them as shown, fread them, and print the width and height. Unfortunatly the width and height come up as incorrect. I'm not sure why. Perhaps a bit/little endian issue? If so I don't know how to fix it. I'm compiling and running it on GCC.
#pragma pack(1)
typedef struct
{
unsigned char fileMarker1; /* 'B' */
unsigned char fileMarker2; /* 'M' */
unsigned int bfSize;
unsigned short unused1;
unsigned short unused2;
unsigned int imageDataO开发者_运维问答ffset; /* Offset to the start of image data */
}FILEHEADER;
typedef struct
{
unsigned int biSize;
signed int width; /* Width of the image */
signed int height; /* Height of the image */
unsigned short planes;
unsigned short bitPix;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
}INFOHEADER;
#pragma pack()
.....
fread( &header, sizeof(FILEHEADER), 1, image );
.....
fread( &iheader, sizeof(INFOHEADER), 1, image );
.....
printf("Width: %i\n", iheader.width);
printf("Height: %i\n", iheader.height);
A Windows bitmap file is indeed stored as little endian. Thus you will need to reverse the endianness of each 2 or 4 byte int value after loading, assuming that your system is big-endian. This IBM article describes various ways to do that.
精彩评论