C++ Program to Read Screen Pixels
Obtaining the color information about the screen pixels is a common operation performed by automation software, which relies on activity on the screen. The process is trivial, and such functionality is incorporated into programming languages with the help of Image/Window reading libraries. This article will teach you how to read screen pixels in C++. The <windows.h> header file could help us to get pixel color.
GetPixel Function
A call to the getpixel function would be made to obtain the color value of the screen pixel, and the coordinates at which the pixel value is to be read would be passed as an argument.
Syntax:
COLORREF GetPixel([in] HDC hdc, [in] int a, [in] int b);
Parameters:
- hdc: handle to a device context (device at which the pixels are to be read. For example, Monitor)
- a: The x-coordinate, in logical units, of the pixel is to be examined.
- b: The y-coordinate, in logical units, of the pixel is to be examined.
Return value: The return value is the COLORREF value that specifies the RGB of the pixel. If the pixel is outside the clipping region, the return value is CLR_INVALID.
Reading Screen Pixels
In the following example, the pixel value for a single pixel will be obtained. This method could be extended to the whole display (using a loop) to obtain the color value of a range of pixels.
Example:
C++
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
HDC dng = GetDC(NULL);
COLORREF c = GetPixel(dng, 10, 150);
cout<< "(" ;
cout<<( int )GetRValue(c)<< ", " ;
cout<<( int )GetGValue(c)<< ", " ;
cout<<( int )GetBValue(c)<< ")" ;
ReleaseDC(NULL, dng);
}
|
Output:
The output of the program
Explanation: Firstly the device context of the display is obtained using the GetDC function with the NULL argument (for the screen). Then a call to the GetPixel function is made, and the device context, along with the coordinates (horizontal and vertical) of the pixel, is sent as an argument. The return data is stored in a COLORREF variable. Later, the Red, Green, and Blue channel values of the pixel are obtained via the GetRValue, GetBValue, and GetGValue functions, which are typecasted to make them appropriate for output. In the end, the display context is released using the ReleaseDC function.
Last Updated :
27 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...