在C语言中没有预定义WORD和DWORD的数据类型,因此我们可以和它们同样字节的数据类型来代替,如下:
typedef unsigned short WORD;
typedef unsigned long DWORD;
typedef long LONG;
typedef unsigned char BYTE;
//文件头结构体
typedef struct tagBITMAPFILEHEADER
{ // bmfh
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
}BITMAPFILEHEADER;
//信息头结构体
typedef struct tagBITMAPINFOHEADER
{ // bmih
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
}BITMAPINFOHEADER;
//调色板项结构体
typedef struct tagRGBQUAD
{ // rgbq
BYTE rgbBlue;
BYTE rgbGreen;
BYTE rgbRed;
BYTE rgbReserved;
}RGBQUAD;
用C语言读入文件头:
int ReadFileHeader(char *filepath,BITMAPFILEHEADER *bmfh)
{
FILE *fp;
//打开文件
fp=fopen(filepath,"rb");
if(!fp)
{ //如果打开失败
printf("Can not open the file:%s\n",filepath);
return -1;
}
//读入bfType
if(fread(&bmfh->bfType,sizeof(WORD),1,fp)!=1)
{
printf("Can not read bfType in the file header.\n");
fclose(fp);
return -1;
}
//读入bfSize
if(fread(&bmfh->bfSize,sizeof(DWORD),1,fp)!=1)
{
printf("Can not read bfSize in the file header.\n");
fclose(fp);
return -1;
}
//读入bfReserved1
if(fread(&bmfh->bfReserved1,sizeof(WORD),1,fp)!=1)
{
printf("Can not read bfReserved1 in the file header.\n");
fclose(fp);
return -1;
}
//读入bfReserved2
if(fread(&bmfh->bfReserved2,sizeof(WORD),1,fp)!=1)
{
printf("Can not read bfReserved2 in the file header.\n");
fclose(fp);
return -1;
}
//读入bfOffBits
if(fread(&bmfh->bfOffBits,sizeof(DWORD),1,fp)!=1)
{
printf("Can not read bfOffBits in the file header.\n");
fclose(fp);
return -1;
}
//关闭文件指针
fclose(fp);
return 0;
}