首页 > 代码库 > bmp头部

bmp头部

因为在解析头部信息的时候遇到一些问题,记录下,以便日后复习,在开发过程中需要获取bmp文件的头部信息,这个这些结构体在windows中有定义了,在Wingdi.h 中,不过在Linux中好像是没有的,需要自己去定义,根据直接复制windows的结构体过来就好了,但是要注意的是这些结构体应该按照1字节对齐,这样才能把头部的信息顺序读写到结构体对象中。

#include <stdio.h>

typedef unsigned int uint32; 
typedef unsigned short uint16; 

#pragma pack(1)
typedef struct tagBITMAPFILEHEADER {
    uint16  bfType;
    uint32 bfSize;
    uint16  bfReserved1;
    uint16  bfReserved2;
    uint32 bfOffBits;
} BITMAPFILEHEADER, *PBITMAPFILEHEADER;

typedef struct tagBITMAPINFOHEADER {
    uint32 biSize;
    uint32  biWidth;
    uint32  biHeight;
    uint16  biPlanes;
    uint16  biBitCount;
    uint32 biCompression;
    uint32 biSizeImage;
    uint32  biXPelsPerMeter;
    uint32  biYPelsPerMeter;
    uint32 biClrUsed;
    uint32 biClrImportant;
} BITMAPINFOHEADER;
#pragma pack()
BITMAPFILEHEADER file_header;
BITMAPINFOHEADER info_header;

FILE *bmpFile = fopen("path", "rb");
// ...
fread(&file_header,sizeof(file_header),1,bmpFile);
fread(&info_header,sizeof(info_header),1,bmpFile);
我随便打开一个bmp文件的16进制信息(vi xx.bmp  %!xxd)
    1 0000000: 424d 38a4 0400 0000 0000 3600 0000 2800  BM8.......6...(.                                                                         
    2 0000010: 0000 6001 0000 2001 0000 0100 1800 0000  ..`... .........              
    3 0000020: 0000 02a4 0400 4500 0000 4500 0000 0000  ......E...E.....              
    4 0000030: 0000 0000 0000

file xx.bmp
xx.bmp: PC bitmap, Windows 3.x format, 352 x 288 x 24

uint16 bfType = 0x4d42;//必须为4d42,如果不是则不是bmp文件                                                                                                                                                     
uint32 bfSize = 0x04a438; //(352 * 288 * 24 / 8 + 54 + 2)                                                            
uint16 bfReserved1 = 0x0;//必须0    
uint16 bfReserved2 = 0x0;//必须0                                       
uint32 bfOffBits = 0x36; //

uint32 biSize = 0x28;                                                              
uint32 biWidth = 0x0160;                                                             
uint32 biHeight = 0x0120;                                                            
uint16 biPlanes = 0x1;                                                            
uint16 biBitCount = 0x18;                                                          
uint32 biCompression = 0x00;                                                       
uint32 biSizeImage = 0x04a402;                                                         
uint32 biXPelsPerMeter = 0x45;                                                     
uint32 biYPelsPerMeter = 0x45;                                                     
uint32 biClrUsed = 0x0;                                                              
uint32 biClrImportant = 0x0;

可以参考http://blog.csdn.net/xqhaha/article/details/9294435