纯C代码写BMP文件

int SaveFileBMP( const char* filename, unsigned char* pixels, int width, int height, int pixelSize )
{
	std::ofstream file;
	file.open( filename, std::ios::out | std::ios::binary );

	BITMAPFILEHEADER	bmfh;			// bitmap file header
	BITMAPINFOHEADER	bmih;			// bitmap info header (windows)

	const int OffBits = 54;

	bmfh.bfReserved1 = 0;
	bmfh.bfReserved2 = 0;
	bmfh.bfType = BITMAP_ID;
	bmfh.bfOffBits = OffBits;		// 头部信息54字节
	bmfh.bfSize = width*height*3 + OffBits;

	memset(&bmih, 0 ,sizeof(BITMAPINFOHEADER));
	bmih.biSize = 40;				// 结构体大小为40
	bmih.biPlanes = 1;
	bmih.biSizeImage = width*height*3;
	bmih.biBitCount = 24;
	bmih.biCompression = 0;
	bmih.biWidth = width;
	bmih.biHeight = height;

	// 1 : write bmfh
	file.write( (const char*)&bmfh, sizeof(BITMAPFILEHEADER) );

	// 2 : write bmih
	file.write( (const char*)&bmih, sizeof(BITMAPINFOHEADER) );
	
	unsigned char* ptr = pixels;

	// 3 : write image pixel data...
	for( int row = height - 1; row >= 0; row-- )
	{
		// RGB 24 BITS
		for( int col = 0; col < width; col++, ptr += pixelSize )	
		{
			// convert rgb (24 bits) pixel into bgr pixel (24 bits)
			RGBTRIPLE pix;
			pix.rgbtRed = ptr[0];
			pix.rgbtGreen = ptr[1];
			pix.rgbtBlue = ptr[2];

			// Write bgr pixel(24 bits)
			file.write( (const char*)&pix, sizeof(RGBTRIPLE));
		}
	}

	file.close();

	return 1;
}

上述函数将RGBA / RGBA 格式的图像数据写成24位的bmp文件,pixelSize 表示像素大小,RGB为3,RGBA为4。

RGBA保存成24位bmp文件需要丢弃alpha通道数据。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值