Awais Chishti
Awais Chishti

Reputation: 395

Trouble using GetDIBits()

the following code that uses GetDIBits() is not giving me the desired output:

#include <windows.h>
#include <iostream>
using namespace std;
int main() {int i; HDC MemDC=CreateCompatibleDC(NULL);
    HBITMAP hBit=(HBITMAP)LoadImage(NULL,(LPCTSTR)"F:\\gBit.bmp",IMAGE_BITMAP,1366,768,LR_CREATEDIBSECTION);
    SelectObject(MemDC,hBit);


    BITMAPINFO bmi;
    bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth=1366;
    bmi.bmiHeader.biHeight=1;
    bmi.bmiHeader.biPlanes=1;
    bmi.bmiHeader.biBitCount=24;
    bmi.bmiHeader.biCompression=BI_RGB;
    bmi.bmiHeader.biSizeImage=0;
    bmi.bmiHeader.biXPelsPerMeter=0;
    bmi.bmiHeader.biYPelsPerMeter=0;
    bmi.bmiHeader.biClrUsed=0;
    bmi.bmiHeader.biClrImportant=0;


    BYTE p[3*1366];
    GetDIBits(MemDC,hBit,500,1,p,&bmi,DIB_RGB_COLORS); //My screen width is 1366 and I want to get the pixels of the 500th line
    for (i=0; i<3*1366; i+=3) {cout<<p[i]<<endl;}
    DeleteObject(hBit);
    ReleaseDC(NULL,MemDC); DeleteDC(MemDC);
}

(gBit.bmp is a 1366x768 bitmap that is entirely white.)

I'm new to C++ and have almost no idea about how to use this function. I was expecting p[i] to be 255 for all i greater than or equal to 0 and less than or equal to 3*1366, since every pixel of gBit is white, but random values are being displayed, most of which are 0. Am I not using this function properly or is the mistake somewhere else?

EDIT: It seems like GetDIBits() fails to save the pixel data in p, since the same values are returned when I remove the line containing GetDIBits(). I did not select hBit into a DC this time. What else could be the problem?

Upvotes: 0

Views: 2271

Answers (3)

Abraxas
Abraxas

Reputation: 131

Even though you only want one line you still need to set the full height in the BITMAPINFO structure:

bmi.bmiHeader.biHeight=768;

Upvotes: 0

user13243542345452
user13243542345452

Reputation: 388

Try changing your BitBlt function third argument to 0 (I'm not quite sure why it is 500 as your bitmap consits only of one scanline).

Also note that since 24bit bitmaps are DWORD aligned (last unused bytes are filled with 0) each scanline consumes a multiple of four bytes, so your file size is not actually 1366*3, but 1368*3.

Upvotes: 0

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6049

The MSFT docs state that: "The bitmap identified by the hbmp parameter must not be selected into a device context when the application calls this function." (http://msdn.microsoft.com/en-us/library/windows/desktop/dd144879%28v=vs.85%29.aspx).
That could be part of the problem.

Also note that you should not call DeleteObject on a bitmap still selected into a DC.

Upvotes: 0

Related Questions