Home Ask Login Register

Developers Planet

Your answer is one click away!

Tibbe February 2016

Get pixel RGB color with XGetPixel on focused window in C++

When i click on my window i get correct x y values from another function. With those values I wan't to get the RGB color value on the window that is currently active and not the whole screen. Right now I think it's reading the whole screen. How can I edit this code to get it work? (the window itself is a Fl_Double_Window using FLTK library).

Image to explain the problem: clicking on territory color

int getRGB(int x, int y)

    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, x, y);
    XFree (image);
    XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), &c);
    cout << c.red/256 << " " << c.green/256 << " " << c.blue/256 << "\n" ;



JvO February 2016

Use the Window handle that is used to render the map in stead of RootWindow(); since you already get the correct x/y coordinates you must have that handle available somewhere.

Tibbe February 2016

I found a way using Fl_BMP_image (gInterface.carte):

void  GetPixelColor(int x, int y,char *r,char *g, char *b) //get RGB color from clicked pixel x,y and returns rgb

    const char*  buf = gInterface.carte->data()[0];
    long index = (y * gInterface.carte->w() * gInterface.carte->d()) + (x * gInterface.carte->d()); // X/Y -> buf index

     if (gInterface.carte->count()==1) { // RGB

            *r = *(buf+index+0);
            *g = *(buf+index+1);
            *b = *(buf+index+2);

            printf("%d, %d : %2d, %d, %d \n", x,y,                                 // hex dump r/g/b
                (unsigned char) *r,
                (unsigned char) *g ,
                (unsigned char) *b );



Post Status

Asked in February 2016
Viewed 2,964 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life