http://www.cnblogs.com/kingmoon/archive/2011/04/18/2020097.html
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
typedef short Int16;
typedef int Int32;
typedef unsigned int UInt32;
typedef unsigned char byte;
//BMP 文件头,14个字节
typedef struct {
Int16 bfType;
UInt32 bfSize;
Int16 bfReserved1;
Int16 bfReserved2;
UInt32 bfOffBits;
} sBMPFileHeader;
//BMP 信息文件头
typedef struct {
UInt32 biSize;
UInt32 biWidth;
UInt32 biHeight;
Int16 biPlanes;
Int16 biBitCount;
UInt32 biCompression;
UInt32 biSizeImage;
Int16 biXPelsPerMeter;
Int16 biYPelsPerMeter;
UInt32 biClrUsed;
UInt32 biClrImportant;
} sBMPInfoHeader;
#include "writeBMP.h"
//功能:本函数用于将RGB数据写入到BMP文件
//参数:
//fileName:保存的BMP文件名
//width: RGB图像的宽度
//pRGB: RGB数据的首地址
//isPlane: 1:表示RGB是按照平面模式在内存中存放的,0表示是按照交织模式存放的
void writeBMP(char * fileName, int width, int height, char * pRGB, int isPlane)
{
/// 分割线 //
//将当前帧保存为BMP文件,BMP文件有3个文件头,BITMAPFILEHEADER,BITMAPINFOHEADER,RGBQUAD表,然后才是真正的图像数据
//真正的图像数据是按照从下到上、从左到右的顺序安排,即坐标零点在图像左下角
//定义文件头
sBMPFileHeader BMPFileHeader;
BMPFileHeader.bfType =0x4d42; //文件类型,必须为“BM” 即十六进制下的0x424d
BMPFileHeader.bfSize = 0 ; //位图文件大小,包括所有的文件头在内
BMPFileHeader.bfReserved1 =0; //无定义
BMPFileHeader.bfReserved2 =0; //无定义
BMPFileHeader.bfOffBits =54; //真正的图像数据的偏移量,即所有的文件头信息的长度
//在不需要颜色表时,BMPFileHeader.bfOffBits =54; 14+40;
//定义信息头
sBMPInfoHeader BMPInfoHeader;
BMPInfoHeader.biSize =40; //该信息头的长度,固定为40
BMPInfoHeader.biWidth =width; //图像的行分辨率
BMPInfoHeader.biHeight =height; //图像的列分辨率
BMPInfoHeader.biPlanes =1; //目标设备的级别,固定为1
BMPInfoHeader.biBitCount =24; //每个像素所占的bit数。1:黑白图像;4:16色图;8:256色;24:真彩色
BMPInfoHeader.biCompression =0; //位图压缩类型,0:未经压缩;
BMPInfoHeader.biSizeImage =0; //实际的位图数据占用的字节数,
int temp_DataSizePerLine =( ( BMPInfoHeader.biWidth * BMPInfoHeader.biBitCount /8 + 3 )/4 ) *4;
//定义为:DataSizePerLine = ( biWidth * biBitCount/8 + 3)/4 * 4
//这是由于微软规定一行像素数据所占的字节数必须为4的整数倍
//biSizeImage = DataSizePerLine * biHeight
int temp_biSizeImage = temp_DataSizePerLine * BMPInfoHeader.biHeight;
BMPInfoHeader.biSizeImage =temp_biSizeImage;//实际的位图数据占用的字节数.
//重新计算BMPFileHeader.bfSize
BMPFileHeader.bfSize = BMPInfoHeader.biSizeImage + BMPFileHeader.bfOffBits;
BMPInfoHeader.biXPelsPerMeter =0; //水平分辨率,单位像素/m
BMPInfoHeader.biYPelsPerMeter =0; //水平分辨率,单位像素/m
BMPInfoHeader.biClrUsed =0; //BMP图像使用的颜色,0表示使用全部颜色,
BMPInfoHeader.biClrImportant =0; //重要的颜色数,此值为0时所有颜色都重要,对于使用调色板的BMP图像来说,当显卡不能够显示所有颜色时,此值将辅助驱动程序显示颜色
//定义颜色表,是RGBQUAD结构的表
//RGBQUAD RGB_ColorTable;
//颜色表的长度由BMPInfoHeader.biClrUsed 指定,若BMPInfoHeader.biClrUsed = 0,则由 BMPInfoHeader.biBitCount 指定。
//即2的BMPInfoHeader.biBitCount 次幂个元素。
//对于24位真彩色位图,不需要颜色表。
//对于8位,则需要256个元素的颜色表。
FILE * outfile;
outfile=fopen(fileName,"wb" );//若文件fream1.bmp存在则打开,并清楚内容;若存在,则建立该文件。
if ( outfile == NULL )// 打开文件
{
printf("Open File Error!\n");
exit(1);
}
//先写文件头
fwrite( & BMPFileHeader , sizeof( sBMPFileHeader ),1,outfile);
fwrite( & BMPInfoHeader , sizeof( sBMPInfoHeader ),1,outfile);
//写RGB的数据时,从下往上,从左往右
}