1

The following script will take a screenshot on a Gnome desktop.

import gtk.gdk

w = gtk.gdk.get_default_root_window()
sz = w.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False, 8, sz[0], sz[1])
pb = pb.get_from_drawable(w, w.get_colormap(), 0, 0, 0, 0, sz[0], sz[1])
if (pb != None):
    pb.save("screenshot.png", "png")
    print "Screenshot saved to screenshot.png."
else:
    print "Unable to get the screenshot."

Now, I've been trying to convert this to C and use it in one of the apps I am writing but so far i've been unsuccessful. Is there any what to do this in C (on Linux)?

Thanks! Jess.

u0b34a0f6ae
  • 48,117
  • 14
  • 92
  • 101
Jessica
  • 2,005
  • 4
  • 28
  • 44
  • Well, i first try with some additions to the GTK (see http://maemo.org/api_refs/5.0/beta/hildon/hildon-Additions-to-GTK+.html and a sample for screenshot in http://maemo.gitorious.org/hildon/hildon/blobs/hildon-2-2/examples/hildon-gtk-window-take-screenshot-sync.c) but that brought a hell of dependencies, then I tried XGetImage (http://tronche.com/gui/x/xlib/graphics/XGetImage.html) but that code needs the Xorg devel libs in order to compile... you can see here a sample of that: http://www.codase.com/search/call?name=xgetimage and now I am stuck – Jessica Jun 15 '10 at 14:27
  • 1
    Translate it literally, `gtk.gdk.get_default_root_window` becomes `gdk_get_default_root_window` etc! – u0b34a0f6ae Jun 15 '10 at 14:39

1 Answers1

3

I tested this and it does work, but there might be a simpler way to go from GdkPixbuf to a png this was just the first one I found. (There's no gdk_pixbuf_save())

#include <unistd.h>
#include <stdio.h>
#include <gdk/gdk.h>
#include <cairo.h>

int main(int argc, char **argv)
{
    gdk_init(&argc, &argv);

    GdkWindow *w = gdk_get_default_root_window();

    gint width, height;
    gdk_drawable_get_size(GDK_DRAWABLE(w), &width, &height);

    GdkPixbuf *pb = gdk_pixbuf_get_from_drawable(NULL, 
                       GDK_DRAWABLE(w), 
                       NULL, 
                       0,0,0,0,width,height);

    if(pb != NULL) {
        cairo_surface_t *surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 
                                                           width, height);
        cairo_t *cr = cairo_create(surf);
        gdk_cairo_set_source_pixbuf(cr, pb, 0, 0);
        cairo_paint(cr);
        cairo_surface_write_to_png(surf, "screenshot.png");
        g_print("Screenshot saved to screenshot.png.\n");
    } else {
        g_print("Unable to get the screenshot.\n");
    }
    return 0;
}

you'd compile like this: (assuming you save it as screenshot.c)

gcc -std=gnu99 `pkg-config --libs --cflags gdk-2.0` screenshot.c -o screenshot

Edit: the stuff to save the pixbuf could also look like: (note I didn't try this out, but it's only one line...) Thanks to kaizer.se for pointing out my fail at doc reading :P

gdk_pixbuf_save(pb, "screenshot.png", "png", NULL, NULL);
Community
  • 1
  • 1
Spudd86
  • 2,986
  • 22
  • 20