简体   繁体   中英

C: Why the output numbers are not in standard RGB range: 0-255 in my program?

With only minimum knowledge of C, I have put together the following code, which I compile on Linux Mint 19 with:

gcc-7 -o getPixelColor getPixelColor.c -L/usr/X11/lib -lX11

and execute without argument:

./getPixelColor

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

void get_pixel_color(Display *d, int x, int y, XColor *color)
{
    XImage *image;
    image = XGetImage(d, RootWindow(d, DefaultScreen(d)), x, y, 1, 1, AllPlanes, XYPixmap);
    color->pixel = XGetPixel(image, 0, 0);
    XFree(image);
    XQueryColor(d, DefaultColormap(d, DefaultScreen(d)), color);
}

int main(int argc, char const *argv[])
{
    Display *disp = XOpenDisplay(":0");
    XColor pixel_color;
    get_pixel_color(disp, 0, 0, &pixel_color);
    printf("%d %d %d\n", pixel_color.red, pixel_color.green, pixel_color.blue);
    return 0;
}

Question:

I have no idea what the why the output numbers are not in standard RGB range: 0-255?

Current output example (taken from the desktop picture, [0,0]):

7683 8484 4097

Expected output (taken with a Windows color picker ran by Wine):

29 32 16

I get that I need to convert the values to standard range, could you advise on the formula then?

From the XColor man page :

The red, green, and blue values are always in the range 0 to 65535 inclusive, independent of the number of bits actually used in the display hardware. The server scales these values down to the range used by the hardware. Black is represented by (0,0,0), and white is represented by (65535,65535,65535).

You should be able to scale them back down through division. eg

printf("%d %d %d\n", pixel_color.red/256, pixel_color.green/256, pixel_color.blue/256);

The XColor structure stores the RGB values within a range of 0 to 65535. There are probably modern monitors, that have more colors than the default range. For displaying, this is scaled down to the appropriate range, which is what you are supposed to do too.

See https://tronche.com/gui/x/xlib/color/structures.html for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM