6

I searched and I understood I'll have to use GetDIBits(). I don't know what to do with the LPVOID lpvBits out parameter.

Could someone please explain it to me? I need to get the pixel color information in a two dimensional matrix form so that I can retrieve the information for a particular (x,y) coordinate pair.

I am programming in C++ using Win32 API.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • possible duplicate of [GetDIBits and loop through pixels using X, Y](http://stackoverflow.com/questions/3688409/getdibits-and-loop-through-pixels-using-x-y) – Raymond Chen Jan 25 '12 at 13:55

2 Answers2

5

first you need a bitmap and open it

HBITMAP hBmp = (HBITMAP) LoadImage(GetModuleHandle(NULL), _T("test.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);

if(!hBmp) // failed to load bitmap
    return false;

//getting the size of the picture
BITMAP bm;
GetObject(hBmp, sizeof(bm), &bm);
int width(bm.bmWidth),
    height(bm.bmHeight);

//creating a bitmapheader for getting the dibits
BITMAPINFOHEADER bminfoheader;
::ZeroMemory(&bminfoheader, sizeof(BITMAPINFOHEADER));
bminfoheader.biSize        = sizeof(BITMAPINFOHEADER);
bminfoheader.biWidth       = width;
bminfoheader.biHeight      = -height;
bminfoheader.biPlanes      = 1;
bminfoheader.biBitCount    = 32;
bminfoheader.biCompression = BI_RGB;

bminfoheader.biSizeImage = width * 4 * height;
bminfoheader.biClrUsed = 0;
bminfoheader.biClrImportant = 0;

//create a buffer and let the GetDIBits fill in the buffer
unsigned char* pPixels = new unsigned char[(width * 4 * height)];
if( !GetDIBits(CreateCompatibleDC(0), hBmp, 0, height, pPixels, (BITMAPINFO*) &bminfoheader, DIB_RGB_COLORS)) // load pixel info 
{ 
    //return if fails but first delete the resources
    DeleteObject(hBmp);
    delete [] pPixels; // delete the array of objects

    return false;
}

int x, y; // fill the x and y coordinate

unsigned char r = pPixels[(width*y+x) * 4 + 2];
unsigned char g = pPixels[(width*y+x) * 4 + 1];
unsigned char b = pPixels[(width*y+x) * 4 + 0]; 

//clean up the bitmap and buffer unless you still need it
DeleteObject(hBmp);
delete [] pPixels; // delete the array of objects

so in short, the lpvBits out parameter is the pointer to the pixels but if it is only 1 pixel you need i suggest to use getpixel to

Marc A.
  • 148
  • 11
ColmanJ
  • 457
  • 2
  • 12
  • 28
1

I'm not sure if this is what you're looking for but GetPixel does pretty much what you need ...at least from i can tell from the function's description

omu_negru
  • 4,642
  • 4
  • 27
  • 38