【发布时间】:2012-01-05 04:28:40
【问题描述】:
我正在尝试捕获屏幕图像以用于截屏。因此我需要一个快速的解决方案,并且不能依赖诸如 import 或 xwd 之类的 shell 程序。
这是我到目前为止编写的代码,但它失败并给了我一个垃圾图像,它似乎只是显示了几张奇怪颜色的图像的碎片。
关于我做错了什么有什么想法吗?
#include <X11/Xlib.h>
#include <X11/X.h>
#include <cstdio>
#include <CImg.h>
using namespace cimg_library;
int main()
{
Display *display = XOpenDisplay(NULL);
Window root = DefaultRootWindow(display);
XWindowAttributes gwa;
XGetWindowAttributes(display, root, &gwa);
int width = gwa.width;
int height = gwa.height;
XImage *image = XGetImage(display,root, 0,0 , width,height,AllPlanes, ZPixmap);
unsigned char *array = new unsigned char[width * height * 3];
unsigned long red_mask = image->red_mask;
unsigned long green_mask = image->green_mask;
unsigned long blue_mask = image->blue_mask;
for (int x = 0; x < width; x++)
for (int y = 0; y < height ; y++)
{
unsigned long pixel = XGetPixel(image,x,y);
unsigned char blue = pixel & blue_mask;
unsigned char green = (pixel & green_mask) >> 8;
unsigned char red = (pixel & red_mask) >> 16;
array[(x + width * y) * 3] = red;
array[(x + width * y) * 3+1] = green;
array[(x + width * y) * 3+2] = blue;
}
CImg<unsigned char> pic(array,width,height,1,3);
pic.save_png("blah.png");
printf("%ld %ld %ld\n",red_mask>> 16, green_mask>>8, blue_mask);
return 0;
}
【问题讨论】:
-
嗨@lalaland,你能分享你的最终代码吗,这支持多显示器吗?
-
@Noitidart 是的,我支持多个显示器。我认为github.com/Lalaland/ScreenCap/blob/master/src/… 可能是正确的文件。不过好几年没碰过代码了。代码写得不好,但如果你想使用它,我会在那里扔一个 BSD 许可证。
-
非常感谢@lalaland 这么快的回复!如果你有时间,我可以在你的问题页面上发布,这样我就可以了解它如何与多显示器一起使用
-
@Noitidart 老实说,我不知道代码是如何工作的。我什至不知道代码是否可以在现代 Linux 系统上运行。
-
啊哈哈谢谢你的注意,我想不是因为我找不到像
XFixesGetCursorImage这样的一些函数
标签: c++ c screenshot xlib cimg