Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ GetDIBits not working

Tags:

c++

winapi

First i load the image "cool.bmp".. load is fine. then i call the function "getPixArray" but it fails.

  case WM_CREATE:// runs once on creation of window
            hBitmap = (HBITMAP)LoadImage(NULL, L"cool.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );
            if(hBitmap == NULL)
                ::printToDebugWindow("Error: loading bitmap\n");
            else 
                BYTE* b = ::getPixArray(hBitmap);     

my getPixArray function

  BYTE* getPixArray(HBITMAP hBitmap)
        {
        HDC hdc,hdcMem;

        hdc = GetDC(NULL);
        hdcMem = CreateCompatibleDC(hdc); 

        BITMAPINFO MyBMInfo = {0};
        // Get the BITMAPINFO structure from the bitmap
        if(0 == GetDIBits(hdcMem, hBitmap, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
        {
            ::printToDebugWindow("FAIL\n");
        }

        // create the bitmap buffer
        BYTE* lpPixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];

        MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
        MyBMInfo.bmiHeader.biBitCount = 32;  
        MyBMInfo.bmiHeader.biCompression = BI_RGB;  
        MyBMInfo.bmiHeader.biHeight = (MyBMInfo.bmiHeader.biHeight < 0) ? (-MyBMInfo.bmiHeader.biHeight) : (MyBMInfo.bmiHeader.biHeight); 

        // get the actual bitmap buffer
        if(0 == GetDIBits(hdc, hBitmap, 0, MyBMInfo.bmiHeader.biHeight, (LPVOID)lpPixels, &MyBMInfo, DIB_RGB_COLORS))
        {
            ::printToDebugWindow("FAIL\n");
        }

        return lpPixels;
    }

This function is supposed to get a reference to the internal pixel array used to draw the image. but both 'FAIL' messages print to the console. Can anyone identify the error or better produce a working version of this function so i can learn from it? ive been stuck for days on this, please help!

This is the were i got most of this code from: GetDIBits and loop through pixels using X, Y

This is the image i used: "cool.bmp" is a 24-bit Bitmap. Width:204 Height: 204 enter image description here

like image 820
Anthony Raimondo Avatar asked Feb 17 '23 07:02

Anthony Raimondo


1 Answers

Your first function call fails because you did not initialise MyBMInfo.bmiHeader.biSize. You need to do this:

...
BITMAPINFO MyBMInfo = {0};
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
// Get the BITMAPINFO structure from the bitmap
if(0 == GetDIBits(hdcMem, hBitmap, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
....

Once you fix that, the rest of the code will work as intended.

like image 91
David Heffernan Avatar answered Feb 20 '23 03:02

David Heffernan