Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a screen pixel's color in x11

Tags:

c++

linux

x11

xlib

I want to get the RGB value of the top/left pixel (0;0) of the whole x11 display.

what I've got so far:

XColor c;
Display *d = XOpenDisplay((char *) NULL);

XImage *image;
image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
c->pixel = XGetPixel (image, 0, 0);
XFree (image);
XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), c);
cout << c.red << " " << c.green << " " << c.blue << "\n";

but I need those values to be 0..255 or (0.00)..(1.00), while they look like 0..57825, which is no format I recognize.

also, copying the whole screen just to get one pixel is very slow. as this will be used in a speed-critical environment, I'd appreciate if someone knows a more performant way to do this. Maybe using XGetSubImage of a 1x1 size, but I'm very bad at x11 development and don't know how to implement that.

what shall I do?

like image 600
nonchip Avatar asked Jul 08 '13 02:07

nonchip


1 Answers

I took your code and got it to compile. The values printed (scaled to 0-255) give me the same values as I set to the desktop background image.

#include <iostream>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

using namespace std;

int main(int, char**)
{
    XColor c;
    Display *d = XOpenDisplay((char *) NULL);

    int x=0;  // Pixel x 
    int y=0;  // Pixel y

    XImage *image;
    image = XGetImage (d, XRootWindow (d, XDefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
    c.pixel = XGetPixel (image, 0, 0);
    XFree (image);
    XQueryColor (d, XDefaultColormap(d, XDefaultScreen (d)), &c);
    cout << c.red/256 << " " << c.green/256 << " " << c.blue/256 << "\n";

    return 0;
}
like image 97
parkydr Avatar answered Sep 20 '22 15:09

parkydr