Convert a GTK python script to C

2020-03-31 08:31发布

问题:

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.

回答1:

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