这是一个更大研究项目的子项目。我试图每100毫秒拍摄一次活动窗口(浏览器)的截图,然后将其存储在内存中以供OpenCV处理。我从一个类似的问题中找到了一个截屏解决方案,目前正在尝试使用它。下面的代码片段似乎可以在拍摄整个桌面截图或特定窗口截图时正常工作,但对于GTK窗口则不起作用。我尝试在Debian Squeeze上拍摄Iceweasel和Nautilus的截图,但它根本不起作用。我是X11的新手,不知道如何检查错误,或者是否有什么我错过的东西,因为这似乎适用于QT窗口。
typedef int (*handler)(Display *, XErrorEvent *);
int handleX11Error(Display *d, XErrorEvent *er)
{
std::cout << "X11 Error: " << er->error_code << std::endl;
}
int main()
{
std::cout << "Sleeping 5 seconds" << std::endl;
// we may need to sleep if we want to focus another window.
sleep(5);
std::cout << "taking screenshot" << std::endl;
Display *display = XOpenDisplay(NULL);
//Window root = DefaultRootWindow(display);
XWindowAttributes gwa;
int revert = RevertToNone;
Window active;
XErrorEvent *error;
handler myHandler = &handleX11Error;
XSetErrorHandler(myHandler);
// X11 - Get Window that has focus
XGetInputFocus(display,&active,&revert);
//XGetWindowAttributes(display, root, &gwa);
if (!XGetWindowAttributes(display, active, &gwa))
std::cout << "XGetWindowAttributes failed" << std::endl;
int width = gwa.width;
int height = gwa.height;
//XImage *image = XGetImage(display,root, 0,0 , width,height,AllPlanes, ZPixmap);
XImage *image = XGetImage(display,active, 0,0 , width,height,XAllPlanes(), ZPixmap);
unsigned char *array = new unsigned char[width * height * 3];
CImg<unsigned char> pic(array,width,height,1,3);
for (int x = 0; x < width; x++){
for (int y = 0; y < height ; y++){
pic(x,y,0) = (XGetPixel(image,x,y) & image->red_mask ) >> 16;
pic(x,y,1) = (XGetPixel(image,x,y) & image->green_mask ) >> 8;
pic(x,y,2) = XGetPixel(image,x,y) & image->blue_mask;
}
}
delete[] array;
pic.save_png("blah.png");
std::cout << "Finished" << std::endl;
return 0;
}
上述代码适用于完整的桌面截图或QT。我没有收到任何错误(不知道我是否正确处理了它们)。只是一张几个字节的空白图片,这让我想到其中一个X函数失败了(XGetInputFocus、XGetWindowAttributes、XGetImage),我认为是XGetFocus没有正常工作。我错过了什么,还是有其他替代方法吗?请注意,我正在运行KDE(4.4.5),如果有任何重要性,请告诉我。
更新:
我尝试使用Qt4进行截图,虽然它可以正常工作,但在尝试从X11获取焦点窗口时也遇到了同样的问题。
int main(int argc, char **argv)
{
sleep(5);
Display *display = XOpenDisplay(NULL);
int revert = RevertToNone;
Window active;
XGetInputFocus(display,&active,&revert);
QApplication app(argc, argv);
QPixmap pixmap = QPixmap::grabWindow(active);
pixmap.save("test.png","PNG");
QPushButton quit("Quit");
quit.resize(75, 30);
quit.setFont(QFont("Times", 18, QFont::Bold));
QObject::connect(&quit, SIGNAL(clicked()), &app, SLOT(quit()));
quit.show();
return app.exec();
}
我相信是XGetInputFocus()出了问题,导致了这个错误。