Click here to Skip to main content
14,546,611 members


Rate this:
4.71 (21 votes)
Please Sign up or sign in to vote.
4.71 (21 votes)
22 Dec 2003
CDibData is a utility class for: loading, saving, and manipulating bitmaps

Image 1


CDibData is a class used to simplify loading, saving, converting (color-depth), and accessing bitmap image bits. It was originally designed as a utility class to allow direct access to the image bits of a bitmap object. Upon realizing that it would be a useful class, on its own, I decided to expand its abilities to include: loading, saving, and conversion of bitmaps. The class does not require that the bitmap be loaded as a DIBSECTION in order to be useful, that was the original requirement when it was created.

I have also included a copy of Quantize.cpp by Jeff Prosise; Quantize.cpp can be found in the MFC library for those interested in reading about it.

Ok after reading this article and testing the code: blast me, find the bugs, tell me how to improve the code and/or Doxygen generated documentation. Do your best to break the code, even you guys in quality control (who specialize in the ridiculous). If there is something wrong, I want to know!


The main references used to develop this were "Programming Windows Fifth Edition" by Charles Petzold, and the MFC library. Most of the references are listed in CDibData.cpp.

Using the Code

The DIB is stored internally in a single block of globally allocated memory suitable for transfer via the clipboard using the CF_DIB format. Since CDibData was not designed as a replacement for CBitmap, it does not maintain a copy of the original bitmap handle.

If you have not installed the Windows SDK from Microsoft, you will get some compilation errors when compiling in debug mode. The reason for this is that BITMAPV5HEADER was not defined in the SDK that came with Visual C++ 6.0. Since BITMAPV5HEADER is only used for displaying debugging information, it should be easy to comment out the code.

Note: When an CDibData object contains a compressed DIB, you no longer have direct access to the image bits. Therefore, you can save the DIB image to file but not convert it or use any function that requires direct access to the image bits.

Examples of how to load a bitmap file:

// Loading file using CDibData::LoadDIB()
// This method also allows for the loading of 2 bits-per-pixels bitmaps by
// converting them to 4 bits-per-pixels when loading.
HBITMAP hBitmap = m_DibData.LoadDIB(lpszPathName);
if( !hBitmap )
    return FALSE;
// Loading file using LoadImage()
HBITMAP hBitmap = (HBITMAP)::LoadImage(
    NULL, lpszPathName, IMAGE_BITMAP,
if( !hBitmap )
    return FALSE;
if( m_Bitmap.Attach(hBitmap) )
// Loading file directly into a CDibData object
// Note: DibXXXX() functions are actually just defined wrappers for
// GlobalXXXX() functions (used internally for debugging).
    // Copy DIB from file
    CFile cf(lpszPathName, CFile::modeRead);

    // Read bitmap file header
    cf.Read((void*)&bmfh, sizeof(BITMAPFILEHEADER));

    // Verify file type
    if( bmfh.bfType != 0x4D42 )
        return NULL;

    // Read DIB from file
    DWORD dwLen = cf.GetLength() - sizeof(BITMAPFILEHEADER);
    hDib = DibAlloc(dwLen);
    pDib = DibLock(hDib);
    if( pDib )
        cf.Read((void*)pDib, (UINT)dwLen);

    if( !pDib )
        if( hDib )
        return NULL;

catch( CFileException* /*e*/)
    if( pDib )
    if( hDib )
    return NULL;

// Attach DIB to this object
if( !Attach(hDib) )
    return NULL;

Examples of how to save a bitmap file:

// Save file using internally stored DIB data.
// Save compressed file using internally stored DIB data.
m_DibData.CreateDIB.SaveDIB(lpszPathName, NULL, TRUE);
// Save file using external bitmap source.
m_DibData.CreateDIB.SaveDIB(lpszPathName, &m_Bitmap);
// Save compressed file using external bitmap source.
m_DibData.CreateDIB.SaveDIB(lpszPathName, &m_Bitmap, TRUE);

Examples of converting from one format to another:

// Convert internally stored DIB data to new format
// Note: Use delete to destroy pDibClass when finished with object
CDibData* pDibClass = m_DibData.GetConvertedDIB(wNewColorDepth);
// Convert internally stored DIB data to new format using palette optimization
CDibData* pDibClass = m_DibData.GetConvertedDIB(wNewColorDepth, TRUE);
// Create converted CDibData object from CBitmap object
CDibData ddObj;
CDibData* pDibClass = ddObj.GetConvertedDIB(wNewColorDepth, TRUE);

Example of 90 degree rotation:

// Create source DIB
CDibData dibSrc;
if( !dibSrc.CreateDIB(&bmpSrc) )
    return FALSE;
int x, y, t;
int cx = dibSrc.GetWidth();
int cy = dibSrc.GetHeight();

BOOL bResult = FALSE;

// Create rotated destination bitmap bits object
CBitmap bmpDest;
    CDC dcDest;
    CBitmap* pOldBitmap = dcDest.SelectObject(&bmpSrc);
    BOOL bRet = bmpDest.CreateCompatibleBitmap(&dcDest, cy, cx);
    if( !bRet )
        return bRet;

CDibData dibDest;
if( !dibDest.CreateDIB(&bmpDest) )
    return FALSE;

// Rotate right (90 degrees)
if( nRotations == 0 )
    for( x = 0; x < cx; ++x )
        t = cy - 1;
        for( y = 0; y < cy; ++y, --t )
            dibDest.CopyPixelValue( t, x, dibSrc, x, y);
// Rotate left (90 degrees)
    for( y = 0; y < cy; ++y )
        t = cx - 1;
        for( x = 0; x < cx; ++x, --t )
            dibDest.CopyPixelValue(y, t, dibSrc, x, y);

// Copy destination bits to destination bitmap
if( !dibDest.SetDIBits(&bmpDest) )
    return FALSE;

Points of Interest

Some of you may be interested in the following:

  • Question: What is with the style used to write the comments proceeding each function?
  • Answer: I decided to use Doxygen to generate documentation for this object. I've used it before to help me understand other peoples code, but never to create accurate documentation of mine. You will find Doxygen.dat in the CDibData directory used by the Doxygen wizard to generate documentation for the CDibData class.
  • Question: Can GetDIBits() be used to convert bitmaps from one format to another?
  • Answer: Yes, but when converting to a lower color depth you loose important color information. The reason for this is that GetDIBits() does no color optimization.
  • Question: Why use CDibData::LoadDIB() instead of LoadImage()?
  • Answer: CDibData::LoadDIB() can load top-down bitmaps and 2 bits-per-pixel bitmaps, LoadImage() cannot. It is my understanding that WinCE supports 2 bits-per-pixel (shades of gray) bitmaps therefore, I decided to support loading, saving, and manipulation of 2 bits-per-pixel bitmaps. Although CDibData recognizes and can manipulate 2 bits-per-pixel bitmaps, it must convert it to 4 bits-per-pixel, when loading, in order to create an HBITMAP handle that can be used by GDI on non-WinCE devices (a.k.a. your monitor).
  • Question: Does CDibData support WinCE?
  • Answer: No, although CDibData supports 2 bits-per-pixel manipulation, it is designed to work on a PC. The main reason for supporting 2 bits-per-pixels is that some one has to create the bitmaps used by WinCE. I would also like to note that CDibData does not remember the original format of the bitmap that was loaded therefore, you will have to convert it back to 2 bits-per-pixels when saving.
  • Question: Does CDibData support the newest bitmap header types?
  • Answer: No, CDibData only supports DIBs with a BITMAPINFOHEADER.
  • Question: Why not use GetBitmapBits() to get access to image bits?
  • Answer: See Q131896 in the MFC library.


This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.


About the Author

John R. Shaw
Software Developer (Senior)
United States United States
I am a senior software engineer who has been designing and developing software for many years, mostly in C/C++. You might say that I think in code; which is why I am passionate about my first rule of coding: “First do no harm”. So if I get carried away in my explanations, please realize that it is just part of my personality. I enjoy learning new things and, when I have the time, passing that knowledge onto others.

Comments and Discussions

GeneralAtta Boy! Pin
Vaclav_27-Jul-09 18:17
MemberVaclav_27-Jul-09 18:17 
QuestionGlobalSize got 0? Pin
liyuncheng15-Apr-08 18:07
Memberliyuncheng15-Apr-08 18:07 
GeneralPerfect solution to my problem Pin
Hal Berman6-Dec-07 12:24
MemberHal Berman6-Dec-07 12:24 
QuestionRe: compiler error Pin
mla15428-Aug-06 5:56
Membermla15428-Aug-06 5:56 
AnswerRe: compiler error Pin
friendwaters6-Aug-08 20:21
Memberfriendwaters6-Aug-08 20:21 
GeneralWin CE issues...Need help! Pin
kissmoses19-Dec-05 7:31
Memberkissmoses19-Dec-05 7:31 
GeneralRe: Win CE issues...Need help! Pin
John R. Shaw20-Dec-05 14:30
MemberJohn R. Shaw20-Dec-05 14:30 
GeneralSlightly Above My Head Pin
8bitgenius11-Oct-05 16:54
Member8bitgenius11-Oct-05 16:54 
GeneralRe: Slightly Above My Head Pin
John R. Shaw12-Oct-05 9:50
MemberJohn R. Shaw12-Oct-05 9:50 
GeneralLoad an Image from an CMemFile Pin
UB90910-Apr-05 4:11
MemberUB90910-Apr-05 4:11 
GeneralRe: Load an Image from an CMemFile Pin
John R. Shaw10-Apr-05 9:04
MemberJohn R. Shaw10-Apr-05 9:04 
GeneralMistake: pImage = pDib + pbmfh-&gt;bfOffBits; Pin
sakee30-Mar-05 21:14
Membersakee30-Mar-05 21:14 
GeneralRe: Mistake: pImage = pDib + pbmfh-&gt;bfOffBits; Pin
John R. Shaw31-Mar-05 20:48
MemberJohn R. Shaw31-Mar-05 20:48 
GeneralRe: Mistake: pImage = pDib + pbmfh-&gt;bfOffBits; Pin
sakee3-Apr-05 20:49
Membersakee3-Apr-05 20:49 
GeneralRe: Mistake: pImage = pDib + pbmfh-&gt;bfOffBits; Pin
John R. Shaw10-Apr-05 8:27
MemberJohn R. Shaw10-Apr-05 8:27 
GeneralProblem in CreateDIB(CBitmap* p_bmp) Pin
jammin PPP22-Feb-05 14:59
Memberjammin PPP22-Feb-05 14:59 
GeneralSetPixel() Pin
super60021-Dec-04 13:24
Membersuper60021-Dec-04 13:24 
GeneralRe: SetPixel() Pin
John R. Shaw22-Dec-04 15:39
MemberJohn R. Shaw22-Dec-04 15:39 
GeneralRe: SetPixel() Pin
super60028-Dec-04 16:22
Membersuper60028-Dec-04 16:22 
GeneralRe: SetPixel() Pin
super60011-Jun-05 21:28
Membersuper60011-Jun-05 21:28 
GeneralTNX big time Pin
Zizilamoroso11-Jun-04 3:19
MemberZizilamoroso11-Jun-04 3:19 
GeneralGood stuff Pin
Niklas Lindquist2-Jun-04 7:54
MemberNiklas Lindquist2-Jun-04 7:54 
GeneralRe: Good stuff Pin
John R. Shaw2-Jun-04 15:35
MemberJohn R. Shaw2-Jun-04 15:35 
GeneralException Pin
Atlence26-Apr-04 0:16
MemberAtlence26-Apr-04 0:16 
GeneralRe: Exception Pin
John R. Shaw27-Apr-04 6:12
MemberJohn R. Shaw27-Apr-04 6:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 22 Dec 2003


52 bookmarked