#define BMP_Header_Length 54
// 写入bmp文件(24位)
int save_bmp_image(int w, int h, unsigned char *pdata, char *BmpFileName, int IsRGBA )
{
int ret = 0;
unsigned char header[BMP_Header_Length] = {
0x42, 0x4d, 0, 0, 0, 0, 0, 0, 0, 0,
54, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, IsRGBA ? 32 : 24, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
};
long file_size = (long)w * (long)h * (IsRGBA ? 4 : 3) + 54;
header[2] = (unsigned char)(file_size &0x000000ff);
header[3] = (file_size >> 8) & 0x000000ff;
header[4] = (file_size >> 16) & 0x000000ff;
header[5] = (file_size >> 24) & 0x000000ff;
long width = w;
header[18] = width & 0x000000ff;
header[19] = (width >> 8) &0x000000ff;
header[20] = (width >> 16) &0x000000ff;
header[21] = (width >> 24) &0x000000ff;
long height = h;
header[22] = height &0x000000ff;
header[23] = (height >> 8) &0x000000ff;
header[24] = (height >> 16) &0x000000ff;
header[25] = (height >> 24) &0x000000ff;
FILE *pWritingFile = NULL;
pWritingFile = fopen(BmpFileName, "wb");
if( pWritingFile == NULL )
{
printf("-----------%s:%d-------------- fopen failed-!\n", __FUNCTION__, __LINE__);
return -1;
}
ret = fwrite(header, sizeof(unsigned char), 54, pWritingFile);
if(ret < 0)
{
printf("-----------%s:%d---ret %d---- fwrite header failed-!\n", __FUNCTION__, __LINE__, ret);
return -1;
}
int BytesPerPixel = IsRGBA ? 4 : 3;
int LineLength, TotalLength;
LineLength = w * BytesPerPixel; // 每行数据长度大致为图象宽度乘以
// 每像素的字节数
while( LineLength % 4 != 0 ) // 修正LineLength使其为4的倍数
++LineLength;
TotalLength = LineLength * h; // 数据总长 = 每行长度 * 图象高度
ret = fwrite(pdata, sizeof(unsigned char), (size_t)(long)TotalLength, pWritingFile);
if(ret < 0)
{
printf("-----------%s:%d---ret %d---- fwrite data failed-!\n", __FUNCTION__, __LINE__, ret);
return -1;
}
// 释放内存和关闭文件
fclose(pWritingFile);
return 0;
}