Getting pixel color in C++

╄→гoц情女王★ 提交于 2019-11-27 14:09:07

问题


I would like to get the RGB values of a pixel at different x, y coordinates on the screen. How would I go about this in C++?

I'm trying to create my own gaussian blur effect.

This would be in Windows 7.

Edit

What libraries need to be included for this to run?

What I have going:

#include <iostream>

using namespace std ;

int main(){

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

    cout << color; 

}

回答1:


As mentioned in a previous post, you want the GetPixel function from the Win32 API.

GetPixel sits inside gdi32.dll, so if you have a proper environment setup, you should be able to include windows.h(which includes wingdi.h) and you should be golden.

If you have a minimal environment setup for whatever reason, you could also use LoadLibrary on gdi32.dll directly.

The first parameter to GetPixel is a handle to the device context, which can be retrieved by calling the GetDC function(which is also available via <windows.h>).

A basic example that loads GetPixel from the dll and prints out the color of the pixel wherever your cursor is is as follows.

#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;
}



回答2:


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

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



来源:https://stackoverflow.com/questions/4839623/getting-pixel-color-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!