在C++中获取像素颜色

rec*_*gle 7 c++ windows rgb winapi pixel

我想在屏幕上的不同x,y坐标处获取像素的RGB值.我将如何在C++中实现这一目标?

我正在尝试创建自己的高斯模糊效果.

这将在Windows 7中.

编辑

需要包含哪些库才能运行?

我要做的:

#include <iostream>

using namespace std ;

int main(){

    HDC dc = GetDC(NULL);
    COLORREF color = GetPixel(dc, 0, 0);
    ReleaseDC(NULL, dc);

    cout << color; 

}
Run Code Online (Sandbox Code Playgroud)

tem*_*def 13

You can use GetDC on the NULL window to get a device context for the whole screen, and can follow that up with a call to GetPixel:

HDC dc = GetDC(NULL);
COLORREF color = GetPixel(dc, x, y);
ReleaseDC(NULL, dc);
Run Code Online (Sandbox Code Playgroud)

Of course, you'd want to only acquire and release the device context once while doing all the pixel-reading for efficiency.


syl*_*ism 7

如前一篇文章所述,您需要Win32 API中的GetPixel函数.

GetPixel位于gdi32.dll中,所以如果你有一个合适的环境设置,你应该能够包含windows.h(包括wingdi.h),你应该是金色的.

如果由于某种原因设置了最小的环境,您也可以直接在gdi32.dll上使用LoadLibrary.

GetPixel的第一个参数是设备上下文的句柄,可以通过调用GetDC函数(也可以通过<windows.h>)来检索.

从dll加载GetPixel并在光标所在的位置打印出像素颜色的基本示例如下所示.

#include<windows.h>
#include<stdio.h>

int main(int argc, char** argv)
{
    FARPROC pGetPixel;

    HINSTANCE _hGDI = LoadLibrary("gdi32.dll");
    if(_hGDI)
    {
        pGetPixel = GetProcAddress(_hGDI, "GetPixel");
        HDC _hdc = GetDC(NULL);
        if(_hdc)
        {
            POINT _cursor;
            GetCursorPos(&_cursor);
            COLORREF _color = (*pGetPixel) (_hdc, _cursor.x, _cursor.y);
            int _red = GetRValue(_color);
            int _green = GetGValue(_color);
            int _blue = GetBValue(_color);

            printf("Red: 0x%02x\n", _red);
            printf("Green: 0x%02x\n", _green);
            printf("Blue: 0x%02x\n", _blue);
        }
        FreeLibrary(_hGDI);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)