捕获数组中的屏幕像素

时间:2019-01-21 15:48:19

标签: c++ winapi gdi

我试图从屏幕上捕获像素到数组,然后以某种方式使用它。我制作了这个简短的程序,只是为了查看捕获是否有效,但似乎没有。我在互联网上看到了很多这样的示例,但是它总是与我的代码相同。也许我错过了一些小错误。有人可以帮我吗?

PS:看起来阵列中的图片有些偏移或翻转,因为我可以看到正确的颜色,但是位置错误。 (在代码中,Y坐标被翻转了,因为我发现它应该是这样的,但是如果没有翻转,它就无法工作)

void ScreenCap(BYTE*& pScreenData, int& iScreenX, int& iScreenY)
{
    iScreenX = GetSystemMetrics(SM_CXSCREEN);
    iScreenY = GetSystemMetrics(SM_CYSCREEN);
    HWND hDesktopWnd = GetDesktopWindow();
    HDC hDesktopDC = GetDC(hDesktopWnd);
    HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
    HBITMAP hCaptureBitmap = CreateCompatibleBitmap(hDesktopDC, iScreenX, iScreenY);
    SelectObject(hCaptureDC, hCaptureBitmap);

    BitBlt(hCaptureDC, 0, 0, iScreenX, iScreenY, hDesktopDC, 0, 0, SRCCOPY | CAPTUREBLT);

    BITMAPINFO bmi = { 0 };
    bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
    bmi.bmiHeader.biWidth = iScreenX;
    bmi.bmiHeader.biHeight = iScreenY;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biCompression = BI_RGB;

    pScreenData = new BYTE[4 * iScreenX * iScreenY];

    GetDIBits(
        hCaptureDC,
        hCaptureBitmap,
        0,
        iScreenY,
        pScreenData,
        &bmi,
        DIB_RGB_COLORS
    );

    ReleaseDC(hDesktopWnd, hDesktopDC);
    DeleteDC(hCaptureDC);
    DeleteObject(hCaptureBitmap);
}
int main()
{
    while (true)
    {
        BYTE* pScreenData = 0;
        int iScreenX, iScreenY;
        ScreenCap(pScreenData, iScreenX, iScreenY);

        std::cout << "Captured screenshot of size: " << iScreenX << " " << iScreenY << std::endl;
        Sleep(1000);

        while (true)
        {
            if (GetAsyncKeyState(VK_SPACE))
            {
                while (GetAsyncKeyState(VK_SPACE));
                break;
            }
            POINT pCursor;
            GetCursorPos(&pCursor);
            const int r = pScreenData[4 * ((iScreenY - pCursor.y - 1) * iScreenX + pCursor.x) + 2]; 
            const int g = pScreenData[4 * ((iScreenY - pCursor.y - 1) * iScreenX + pCursor.x) + 1];
            const int b = pScreenData[4 * ((iScreenY - pCursor.y - 1) * iScreenX + pCursor.x) + 0];
            const int a = pScreenData[4 * ((iScreenY - pCursor.y - 1) * iScreenX + pCursor.x) + 3];
            std::cout << pCursor.x << " " << pCursor.y << ": " << r << " " << g << " " << b << " " << a << std::endl;
            Sleep(200);
        }

        delete[] pScreenData;
    }
    return 0;
}

0 个答案:

没有答案