c – GetDIBits并使用X,Y循环显示像素

我抓住屏幕的一部分并扫描像素以获得特定的颜色范围.

我查看了 MSDN’s Capturing an Image 示例并知道如何使用这些函数.

我可以把这些比特放到一个数组中,但是我不知道如何以这样的方式做到这一点我可以循环遍历它,就像我的图像一样.一个伪示例(我肯定是远离的):

for ( x = 1; x <= Image.Width; x += 3 )
{
    for ( y = 1; y <= Image.Height; y += 3 )
    {
        red = lpPixels[x];
        green = lpPixels[x + 1];
        blue = lpPixels[x + 2];
    }
}

这基本上就是我想做的事情,所以如果红色,蓝色和绿色是某种颜色,我会知道图像中(x,y)的坐标是什么.

我只是不知道如何以这种方式使用GetDIBits,以及如何适当地设置数组以便能够实现这一点.

除了已经给出的好答案之外,这里有一个如何让一个简单的数组结构继续前进的例子. (您可以使用例如 Goz’ code

进行迭代.)

GetDIBits reference @ MSDN

您必须选择DIB_RGB_COLORS作为uUsage的标志,并设置它包含的 BITMAPINFO structure BITMAPINFOHEADER structure .将biClrUsed和biClrImportant设置为零时,会出现“no”颜色表,因此您可以将GetDIBits获取的位图像素作为RGB值串行读取.使用32作为位计数(biBitCount)根据MSDN设置数据结构:

The bitmap has a maximum of 2^32 colors. If the biCompression member of the BITMAPINFOHEADER is BI_RGB , the bmiColors member of BITMAPINFO is NULL . Each DWORD in the bitmap array represents the relative intensities of blue, green, and red, respectively, for a pixel. The high byte in each DWORD is not used.

由于MS LONG正好是32位长(DWORD的大小),因此您不必注意填充(如 Remarks section 中所述).

码:

HDC hdcSource = NULL; // the source device context
HBITMAP hSource = NULL; // the bitmap selected into the device context

BITMAPINFO MyBMInfo = {0};
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);

// Get the BITMAPINFO structure from the bitmap
if(0 == GetDIBits(hdcSource, hSource, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
{
    // error handling
}

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

// We'll change the received BITMAPINFOHEADER to request the data in a
// 32 bit RGB format (and not upside-down) so that we can iterate over
// the pixels easily. 

// requesting a 32 bit image means that no stride/padding will be necessary,
// although it always contains an (possibly unused) alpha channel
MyBMInfo.bmiHeader.biBitCount = 32;
MyBMInfo.bmiHeader.biCompression = BI_RGB;  // no compression -> easier to use
// correct the bottom-up ordering of lines (abs is in cstdblib and stdlib.h)
MyBMInfo.bmiHeader.biHeight = abs(MyBMInfo.bmiHeader.biHeight);

// Call GetDIBits a second time, this time to (format and) store the actual
// bitmap data (the "pixels") in the buffer lpPixels
if(0 == GetDIBits(hdcSource, hSource, 0, MyBMInfo.bmiHeader.biHeight,
                  lpPixels, &MyBMInfo, DIB_RGB_COLORS))
{
    // error handling
}
// clean up: deselect bitmap from device context, close handles, delete buffer

翻译自:https://stackoverflow.com/questions/3688409/getdibits-and-loop-through-pixels-using-x-y