Getting Bitmap pixel values using the Windows GetDIBits function

Olumide picture Olumide · Dec 28, 2011 · Viewed 9.6k times · Source

I'm trying to get the pixels of a bitmap using the GetDIBits function. As I have not studied the Windows GDI/API, I'm very unsure about the first argument, HDC. I've searched countless posts here on SO and the web but have been unable to find information or example about how to initialize HDC in this specific case. Here's how far I've gone reading pixel values:

    HBITMAP hBitmap = (HBITMAP) LoadImage(0, L"C:/tmp/Foo.bmp" ,IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    // check hBitmap for error

    BITMAP bm;
    ::GetObject( hBitmap , sizeof(bm) , &bm );

    // TODO: GetDIBits()


Solution:

After scouring the web some more I've been able to cobble together the following:

    /* Omitting error checks for brevity */
    HDC dcBitmap = CreateCompatibleDC ( NULL );
    SelectObject( dcBitmap, hBitmap );

    BITMAPINFO bmpInfo;
    bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmpInfo.bmiHeader.biWidth = bm.bmWidth;
    bmpInfo.bmiHeader.biHeight = -bm.bmHeight;
    bmpInfo.bmiHeader.biPlanes = 1;
    bmpInfo.bmiHeader.biBitCount = 24;
    bmpInfo.bmiHeader.biCompression = BI_RGB;        
    bmpInfo.bmiHeader.biSizeImage = 0;        

    COLORREF* pixel = new COLORREF [ bm.bmWidth * bm.bmHeight ];
    GetDIBits( dcBitmap , hBitmap , 0 , bm.bmHeight , pixel , &bmpInfo , DIB_RGB_COLORS );

Answer

Adrian McCarthy picture Adrian McCarthy · Dec 28, 2011

The source bitmap is typically a device-dependent bitmap. Although it's less common nowadays, that might mean that the bitmap's pixel values are stored as indexes into a color table. In those cases GetDIBits would need access to the color table, which is stored in a device context.

If your bitmap uses RGB values instead of indexes, then the device context should be irrelevant, though in my experience you must still provide a valid one (see What is the HDC for in GetDIBits?), perhaps it looks at other aspects of the device context, like the color depth.