1

I'm storing image rgb data from an HDC bitmap in a 3d array by iterating through each pixel using GetPixel(hdc, i, j).

It works but this function is incredibly slow, however. Even for large images (1920x1080=6,220,800 values, excluding alpha), it should not be taking as long as it is.

I've looked online for alternatives to this but none of them are very clean / readable, at least to me.

Basically I want an hdc bitmap to be copied to an unsigned char the_image[rows][columns][3] more quickly.

Here is the current code. I need help improving the code under //store bitmap in array

// copy window to bitmap
HDC     hScreen = GetDC(window);
HDC     hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, 256, 256);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL    bRet = BitBlt(hDC, 0, 0, 256, 256, hScreen, 0, 0, SRCCOPY);

//store bitmap in array
unsigned char the_image[256][256][3];
COLORREF pixel_color;
for (int i = 0; i < 256; i++) {
    for (int j = 0; j < 256; j++) {
        pixel_color = GetPixel(hDC, i, j);
        the_image[i][j][0] = GetRValue(pixel_color);
        the_image[i][j][1] = GetGValue(pixel_color);
        the_image[i][j][2] = GetBValue(pixel_color);
    }
}

// clean up
SelectObject(hDC, old_obj);
DeleteDC(hDC);
ReleaseDC(NULL, hScreen);
DeleteObject(hBitmap);
oguz ismail
  • 1
  • 16
  • 47
  • 69
ddxm
  • 103
  • 6

1 Answers1

0

Thanks to Raymond Chen for introducing the "GetDIBits" function, and this other thread, I finally managed to get it working.

It's pretty much instantaneous compared to before, although I'm getting some problems with exceeding stack size for large images, should be a fairly easy fix though. Here's the code that replaces what's under "//store bitmap in array":

BITMAPINFO MyBMInfo = { 0 };
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
GetDIBits(hDC, hBitmap, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS);
MyBMInfo.bmiHeader.biBitCount = 24;
MyBMInfo.bmiHeader.biCompression = BI_RGB;
MyBMInfo.bmiHeader.biHeight = abs(MyBMInfo.bmiHeader.biHeight);
unsigned char the_image[256][256][3];
GetDIBits(hDC, hBitmap, 0, MyBMInfo.bmiHeader.biHeight,
    &the_image[0], &MyBMInfo, DIB_RGB_COLORS);
ddxm
  • 103
  • 6