The difference between a BITMAP and a DIB

There is much confusion about bitmap handles (HBITMAP) and device independent bitmaps (DIB). The terms are often interchanged and functions that you would expect to return a DIB, such as CreateDIBitmap, do in fact return a value of type HBITMAP.

HBITMAP’s are handles to memory objects containing a BITMAP structure followed by palette information and bitmap data and should be processed by ScanBarCodeFromBitmap:

DIB’s are handles to memory objects that have the same format as a BMP file minus the file header (BITMAPFILEHEADER) and should be processed by ScanBarCodeFromDIB. The following MFC C++ code can be used to load a small BMP file into a DIB:

#include <limits.h>

// Simple function to load a BMP file into a DIB. This assumes that the file is smaller than UINT_MAX.

 

HGLOBAL LoadDIB( LPCSTR sBMPFile)

{

CFile file;

 

if( !file.Open( sBMPFile, CFile::modeRead) )

return NULL;

 

BITMAPFILEHEADER bmfHeader;

ULONGLONG nFileLen;

 

nFileLen = file.GetLength();

 

if (nFileLen > UINT_MAX)

{

AfxMessageBox(“File is too big to load with a single read”);

return NULL ;

}

 

// Read file header and ignore

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;

 

HGLOBAL hDIB = ::GlobalAlloc(GMEM_FIXED, (SIZE_T) nFileLen);

if (hDIB == 0)

return NULL;

 

// Read the remainder of the bitmap file.

if (file.Read((LPSTR)hDIB, (UINT) nFileLen – sizeof(BITMAPFILEHEADER)) !=

(UINT) nFileLen – sizeof(BITMAPFILEHEADER) )

{

::GlobalFree(hDIB);

return NULL;

}

 

return hDIB;

}

 

The following wikipedia article contains a more detailed explanation: http://en.wikipedia.org/wiki/BMP_file_format