如何将 HDC 位图快速复制到三维阵列?

How can an HDC bitmap be copied to a 3-dimensional array quickly?

本文关键字:复制 三维 阵列 HDC 位图      更新时间:2023-10-16

我通过使用GetPixel(hdc, i, j)遍历每个像素,将来自 HDC 位图的图像 rgb 数据存储在 3D 数组中。

它可以工作,但是此功能非常慢。即使对于大图像(1920x1080=6,220,800 值,不包括 alpha),也不应该花费那么长时间。

我在网上寻找过替代方案,但它们都不是很干净/可读,至少对我来说是这样。

基本上,我希望更快地将hdc位图复制到unsigned char the_image[rows][columns][3]

这是当前代码。我需要帮助改进//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);

感谢Raymond Chen引入"GetDIBits"函数,以及另一个线程,我终于设法让它工作了。

与以前相比,它几乎是即时的,尽管我在超过大图像的堆栈大小时遇到了一些问题,但应该是一个相当容易的修复。以下是替换"//在数组中存储位图"下的内容的代码:

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);