2011-10-12 130 views
0

我最近制作了一个程序来读取BMP文件的fileheader和infoheader。我如图所示包装它们,并将其打印出来并打印宽度和高度。不幸的是,宽度和高度出现不正确。我不知道为什么。也许有点/小端问题?如果是这样,我不知道如何解决它。我正在GCC上编译和运行它。阅读BMP头文件,打包。读取不正确的值

#pragma pack(1) 

typedef struct 
{ 
    unsigned char fileMarker1;  /* 'B' */      
    unsigned char fileMarker2;  /* 'M' */ 
    unsigned int bfSize;    
    unsigned short unused1;   
    unsigned short unused2;   
    unsigned int imageDataOffset; /* 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); 
+0

什么是图像的实际尺寸,以及您得到的是什么值。看看他们在十六进制,看看它是否是一个endianess问题 – James

+0

是你的系统大endian?你的系统是什么? –

+0

是否在读取图像数据前先移动到图像数据的开头?数据的偏移量在FILEHEADER中指定。 fileMarker1和fileMarker2的值是否正确? – sashang

回答

1

一个Windows位图文件确实保存作为小端。因此,假设你的系统是big-endian,你需要在加载之后反转每个2或4字节int值的字节序。这IBM article描述了各种方式来做到这一点。