我在使用BitBlt()尝试捕获位于屏幕确切中心的全宽和1像素高的图像时遇到问题。

HDC hdcTemp;
BYTE* bitPointer;
int x, y;
int red, green, blue, alpha;

HDC desktopWindow = GetDC(HWND_DESKTOP);
//GetWindowRect(hWND_Desktop, &rect);
int screenWidth = GetSystemMetrics(SM_CXSCREEN);
int screenHeight = GetSystemMetrics(SM_CYSCREEN);
int wPos = screenWidth / 2;
int hPos = screenHeight / 2;
int screenShotWidth = screenWidth;
int screenShotHeight = 1;

while (true)
{

    hdcTemp = CreateCompatibleDC(desktopWindow);
    BITMAPINFO bitmap;
    bitmap.bmiHeader.biSize = sizeof(bitmap.bmiHeader);
    bitmap.bmiHeader.biWidth = screenShotWidth;
    bitmap.bmiHeader.biHeight = screenShotHeight;
    bitmap.bmiHeader.biPlanes = 1;
    bitmap.bmiHeader.biBitCount = 24;
    bitmap.bmiHeader.biCompression = BI_RGB;
    bitmap.bmiHeader.biSizeImage = screenShotWidth * 4 * screenShotHeight;
    bitmap.bmiHeader.biClrUsed = 0;
    bitmap.bmiHeader.biClrImportant = 0;
    HBITMAP hBitmap2 = CreateDIBSection(hdcTemp, &bitmap, DIB_RGB_COLORS, (void**)(&bitPointer), NULL, NULL);
    SelectObject(hdcTemp, hBitmap2);
    BitBlt(hdcTemp, 0, 0, screenShotWidth, screenShotHeight, desktopWindow, 0, hPos-1 ,SRCCOPY);

    for (int i = 0; i < (screenShotWidth * 4 * screenShotHeight); i += 4)
    {
        red = (int)bitPointer[i];
        green = (int)bitPointer[i + 1];
        blue = (int)bitPointer[i + 2];

        x = i / (4 * screenShotHeight);
        y = i / (4 * screenShotWidth);
        std::cout << "r : " << red << " x: " << x <<  " y: " << y <<  "\n";
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(2));
}


我知道在使用全屏caputre时,BitBlt()需要看起来像这样:

BitBlt(hdcTemp, 0, 0, screenWidth, screenHeight, desktopWindow, 0, 0 ,SRCCOPY);


我只是没有真正做出改变以使其仅捕获我想要捕获的部分,而该部分位于屏幕中间...

最佳答案

bitmap.bmiHeader.biSizeImage = screenShotWidth * 4 * screenShotHeight;


对于24位的位图大小,应按以下方式计算:

int size = ((screenShotWidth * 24 + 31) / 32) * 4 * screenShotHeight;


请注意,24位位图没有alpha通道,每个像素3个字节。将增量更改为以下值:

for(int i = 0; i < (screenShotWidth * 3 * screenShotHeight); i += 3)
{
    red = (int)bitPointer[i];
    green = (int)bitPointer[i + 1];
    blue = (int)bitPointer[i + 2];
    ...
}


为了使事情变得简单,您还可以使用32位位图。

关于c - 使用位图(C)仅捕获屏幕的一部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46120159/

10-15 16:37