如何在x11中获得屏幕像素的颜色

时间:2013-07-08 02:59:36

标签: c++ linux x11 xlib

我想得到整个x11显示器的顶部/左侧像素(0; 0)的RGB值。

到目前为止我得到了什么:

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";

但我需要这些值为0..255(0.00)..(1.00),而他们看起来像0..57825 ,这不是我认可的格式。

另外,复制整个屏幕只是为了获得一个像素非常慢。因为这将用于速度关键的环境,如果有人知道更高效的方式,我会很感激。也许使用1x1大小的XGetSubImage,但我在x11开发方面非常糟糕,并且不知道如何实现它。

我该怎么办?

2 个答案:

答案 0 :(得分:10)

我拿了你的代码然后把它编译好了。打印的值(缩放到0-255)给出的值与我设置到桌面背景图像的值相同。

#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;
}

答案 1 :(得分:2)

来自XColor(3)手册页:

  

红色,绿色和蓝色值始终在0到65535(含)范围内,与显示硬件中实际使用的位数无关。服务器将这些值缩小到硬件使用的范围。黑色由(0,0,0)表示,白色由(65535,65535,65535)表示。在某些函数中,flags成员控制使用红色,绿色和蓝色成员中的哪一个,并且可以是DoRed,DoGreen和DoBlue中零个或多个的包含OR。

因此,您必须将这些值缩放到您想要的任何范围。

相关问题