BMP文件格式图解

BMP格式简单的说就是「File Header + Info Header + (optional palette) + Raw Data」,不过「File Header + Info Header + Raw Data」比较多,故以此格式为例。

FILE HEADER 实例图解14 bytes

typedef struct { 
/* type : Magic identifier,一般为BM(0x42,0x4d) */ 
unsigned short int type; 
unsigned int size;/* File size in bytes,全部的档案大小 */ 
unsigned short int reserved1, reserved2; /* 保留位 */ 
unsigned int offset;/* Offset to image data, bytes */ 
} FILEHEADER;

  1. type:2 bytes,一般都是'B' (0x42)、'M' (0x4D)
  2. size:4 bytes,记录该BMP档的大小,0x436 = 1078 bytes
  3. reserved1:保留位,2 bytes
  4. reserved2:保留位,2 bytes
  5. offset:4 bytes,0x36 = 54 bytes

INFO HEADER 实例图解40 bytes

typedef struct { 
unsigned int size;/* Info Header size in bytes */ 
int width,height;/* Width and height of image */ 
unsigned short int planes;/* Number of colour planes */ 
unsigned short int bits; /* Bits per pixel */ 
unsigned int compression; /* Compression type */ 
unsigned int imagesize; /* Image size in bytes */ 
int xresolution,yresolution; /* Pixels per meter */ 
unsigned int ncolours; /* Number of colours */ 
unsigned int importantcolours; /* Important colours */ 
} INFOHEADER;

  1. size:4 bytes,0x28 = 40 bytes,表示Info Header的大长度总共 40 bytes
  2. width:4 bytes,0x10 = 16,图像宽度为16 pixel
  3. height:4 bytes,0x10 = 16,图像高度为16 pixel
  4. planes:2 bytes,0x01 = 1,位元面数为1
  5. bits:2 bytes,0x20 = 32,每個pixel需要32bits
  6. compression:4 bytes,0代表不压缩
  7. imagesize:4 bytes,0x400 = 1024 bytes,点阵图资料大小为1024 bytes
  8. xresolution:4 bytes,水平解析度
  9. yresolution:4 bytes,垂直解析度
  10. ncolours:4 bytes,点阵图使用的调色板颜色数
  11. importantcolours:4 bytes,重要的颜色数

RAW DATA 实例图解

刚刚的File Header共14bytes,Info Header为40bytes,「imagesize」 = 1024 bytes,所以「14 + 40 + 1024 = 1078」, 即等于File Header中「size」的大小。下面我只提取部分的资料,反正全部的档案,減去Header档54位元组,剩下的就是点阵图的资料。

在Info Header中的「bits」为32 bits,故四个位元组一组,若24 bits,则三个位元组一组,例子中的长宽各为16,以「Z」字型来看,一列则为16组,即16 X 4 = 64 bytes。注意的是,图中是以A、B、C ~ …的读取顺序来解说,但实际上程序所读取到的通常回是反过来的,即… ~ C、B、A。另外,下图是以「BGRA」排列。

原文地址:https://www.cnblogs.com/huxingkeji/p/2772096.html