纯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通道数据。

你可能感兴趣的:(纯C代码写BMP文件)