Writing a bitmap to a BMP file


Writing a bitmap to a BMP file is fairly simple if we have a handle to device-independent bitmap. We simply write BITMAPINFOHEADER information followed by the contents of the bitmap. The three fields that we have to set in the BITMAPINFOHEADER are the bfType which should always be "BM", the bfSize which is the size of the bitmap including the infoheader and the bfOffBits which is the offset to the bitmap bits from the start of the file.

If you have a device-dependent bitmap to begin with, you have to first create a DIB from it. Creating a DIB from a DDB has already been covered in another section.

// WriteDIB		- Writes a DIB to file
// Returns		- TRUE on success
// szFile		- Name of file to write to
// hDIB			- Handle of the DIB
BOOL WriteDIB( LPTSTR szFile, HANDLE hDIB)
{
	BITMAPFILEHEADER	hdr;
	LPBITMAPINFOHEADER	lpbi;

	if (!hDIB)
		return FALSE;

	CFile file;
	if( !file.Open( szFile, CFile::modeWrite|CFile::modeCreate) )
		return FALSE;

	lpbi = (LPBITMAPINFOHEADER)hDIB;

	int nColors = 1 << lpbi->biBitCount;

	// Fill in the fields of the file header 
	hdr.bfType		= ((WORD) ('M' << 8) | 'B');	// is always "BM"
	hdr.bfSize		= GlobalSize (hDIB) + sizeof( hdr );
	hdr.bfReserved1 	= 0;
	hdr.bfReserved2 	= 0;
	hdr.bfOffBits		= (DWORD) (sizeof( hdr ) + lpbi->biSize +
						nColors * sizeof(RGBQUAD));

	// Write the file header 
	file.Write( &hdr, sizeof(hdr) );

	// Write the DIB header and the bits 
	file.Write( lpbi, GlobalSize(hDIB) );

	return TRUE;
}



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • 10 Rules that Make or Break Enterprise App Development Projects In today's app-driven world, application development is a top priority. Even so, 68% of enterprise application delivery projects fail. Designing and building applications that pay for themselves and adapt to future needs is incredibly difficult. Executing one successful project is lucky, but making it a repeatable process and strategic advantage? That's where the money is. With help from our most experienced project leads and software engineers, …

  • Adaptation and evolution are fundamental requirements of survival -- not only in nature, but also in business. Our world has changed dramatically in a short amount of time. Many businesses are fueling and capitalizing on this change, while others are desperately clinging to a bygone era. Who is left standing in the years and decades ahead should come as no surprise. This edition of Unleashing IT highlights the companies that are embracing new circumstances, new methods, and new opportunities. By downloading …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds