void RGBDataSaveAsBmpFile(
const char * bmpFile, // BMP文件名称
unsigned char * pRgbData, // 图像数据
int width, // 图像宽度
int height, // 图像高度
int biBitCount, // 位图深度
bool flipvertical) // 图像是否需要垂直翻转
{
int size = 0;
int bitsPerPixel = 3;
if (biBitCount == 24)
{
bitsPerPixel = 3;
size = width * height * bitsPerPixel * sizeof(char); // 每个像素点3个字节
}
else if (biBitCount == 32)
{
bitsPerPixel = 4;
size = width * height * bitsPerPixel * sizeof(char); // 每个像素点4个字节
}
else return;
// 位图第一部分,文件信息
BITMAPFILEHEADER bfh;
bfh.bfType = (WORD)0x4d42; //图像格式 必须为'BM'格式
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//真正的数据的位置
bfh.bfSize = size + bfh.bfOffBits;
bfh.bfReserved1 = 0;
bfh.bfReserved2 = 0;
BITMAPINFOHEADER bih;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = width;
if (flipvertical)
bih.biHeight = -height;//BMP图片从最后一个点开始扫描,显示时图片是倒着的,所以用-height,这样图片就正了
else
bih.biHeight = height;
bih.biPlanes = 1;
bih.biBitCount = biBitCount;
bih.biCompression = BI_RGB;
bih.biSizeImage = size;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
FILE * fp = NULL;
fopen_s(&fp, bmpFile, "wb");
if (!fp)
return;
fwrite(&bfh, 8, 1, fp);
fwrite(&bfh.bfReserved2, sizeof(bfh.bfReserved2), 1, fp);
fwrite(&bfh.bfOffBits, sizeof(bfh.bfOffBits), 1, fp);
fwrite(&bih, sizeof(BITMAPINFOHEADER), 1, fp);
fwrite(pRgbData, size, 1, fp);
fclose(fp);
}