开发者

Getting pixel color in C++

开发者 https://www.devze.com 2023-02-07 17:04 出处:网络
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 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; 

}


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.


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 at your current cursor position is as follows.

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

typedef WINAPI COLORREF (*GETPIXEL)(HDC, int, int);

int main(int argc, char** argv)
{

    HINSTANCE _hGDI = LoadLibrary("gdi32.dll");
    if(_hGDI)
    {
        while(true) {
            GETPIXEL pGetPixel = (GETPIXEL)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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消