用Xlib API 截图(Snapshot)

风行水上 @ 2012-01-10 00:56:49
标签:

    在X Window环境下,如果要截图,可以通过XGetImage函数获得某个窗口特定区域的像素图。获得图形数据后,就主要是图片处理的工作了。

    下面的程序把结果保存为一种基于文本的图片格式——ppm。ppm文件可以用程序xview或kview打开。

    int window2ppm(Window window, int x, int y, int width, int height){
        XImage* ximg = XGetImage(display, window, x, y, width, height, AllPlanes, ZPixmap);
    
        unsigned long red_mask   = ximg->red_mask;
        unsigned long green_mask = ximg->green_mask;
        unsigned long blue_mask  = ximg->blue_mask;
    
        const char *ofile = Tcl_GetString(objv[2]);
        FILE *fout = fopen(ofile, "w");
    
        fprintf(fout, "P3 %d %d %d\n", width, height, blue_mask);
        fprintf(fout, "# depth = %d\n", ximg->depth);
        fprintf(fout, "# mask  = %04x %04x %04x\n", red_mask, green_mask, blue_mask);
        int nbits_mask = ximg->depth/3;
        //TODO: if bits per color not the same?
        for (int yp=0; yp<pheight; yp++) {
          for (int xp=0; xp<pwidth; xp++) {
            unsigned long pix = XGetPixel(ximg, xp, yp);
            unsigned int red   = (pix & red_mask)  >> (nbits_mask + nbits_mask);
            unsigned int green = (pix & green_mask)>> nbits_mask;
            unsigned int blue  = pix & blue_mask;
            fprintf(fout, "%ld %ld %ld\n", red, green, blue);
          }
        }
        fclose(fout);
        XDestroyImage(ximg);
        return 1;
    }
    

    X Window中关于图形的一些概念

    XImage有几种不同的格式:

    • ZPixmap 的储存方式是一个pixel接着一个pixel存放
    • XYPixmap 则是plane接着plane, 所有pixel特定plane的内容集成bitmap, 各plane再依次排列
    • XYBitmap是只有一个plane的“特殊”XYPixmap

    所谓plane,是指一个pixel需要占用的bit的数目。

    标签:

      分享到:
      comments powered by Disqus

      26/29ms