A Journey 2 Eternity

Create DIB section from a BMP file

Posted on: September 22, 2008

/*
 * Creates a DIB section from a BMP file
 *
 * lpszFileName : Name of the BMP file
 * ppvBits : Receive address of bitmap bits
 * hSection : Optional handle to a file mapping object
 * dwOffset : Offset to the bitmap bit values within hSection
 */

HBITMAP LoadDIBSectionFromFile( LPCTSTR lpszFileName, LPVOID *ppvBits /*= NULL*/, HANDLE hSection /*= NULL*/, DWORD dwOffset /*= 0*/)
{
	LPVOID lpBits;
	CFile file;
	
	if( !file.Open( lpszFileName, CFile::modeRead) ) {
		return NULL;
	}

	BITMAPFILEHEADER bmfHeader;
	long nFileLen = file.GetLength();

	// Read file header
	if (file.Read((LPSTR)&bmfHeader, sizeof(bmfHeader)) != sizeof(bmfHeader)) {
		return NULL;
	}

	// File type should be ‘BM’
	if (bmfHeader.bfType != ((WORD) ( ‘M’ << 8 ) | ‘B’ )) {
		return NULL;
	}

	BITMAPINFO *pbmInfo = (BITMAPINFO *)::GlobalAlloc(GMEM_FIXED, sizeof(BITMAPINFO) + sizeof(RGBQUAD)*256 );
	if (pbmInfo == NULL) {
		return NULL;
	}

	// Read the BITMAPINFO
	file.Read( pbmInfo, sizeof(BITMAPINFO) + sizeof(RGBQUAD)*256 );
	
	BITMAPINFO &bmInfo = *pbmInfo ;
	HBITMAP hBmp = CreateDIBSection( NULL, pbmInfo, DIB_RGB_COLORS, &lpBits, hSection, dwOffset );

	LPBYTE lpDIBBits; // Pointer to DIB bits
	int nColors = bmInfo.bmiHeader.biClrUsed ? bmInfo.bmiHeader.biClrUsed : 1 << bmInfo.bmiHeader.biBitCount;
	if( bmInfo.bmiHeader.biBitCount > 8 ) {
		lpDIBBits = (LPBYTE)((LPDWORD)(bmInfo.bmiColors + bmInfo.bmiHeader.biClrUsed) + ((bmInfo.bmiHeader.biCompression == BI_BITFIELDS) ? 3 : 0));
	} else {
		lpDIBBits = (LPBYTE)(bmInfo.bmiColors + nColors);
	}

	int nOffset = sizeof(BITMAPFILEHEADER) + (lpDIBBits – (LPBYTE)pbmInfo);
	
	file.Seek( nOffset, CFile::begin);
	file.ReadHuge((LPSTR)lpBits, nFileLen – nOffset); //bmInfo.biSizeImage );
	
	::GlobalFree(pbmInfo);
	
	if( ppvBits ) {
		*ppvBits = lpBits;
	}

	return hBmp;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

September 2008
M T W T F S S
« Aug   Dec »
1234567
891011121314
15161718192021
22232425262728
2930  

Blog Stats

  • 26,968 hits
%d bloggers like this: