How to properly get pixbuf from gtkDtrawingArea

Hello everyone.
I’m looking for the best way to get pixbuf from a GtkDrawingArea.
I see two methods to do that.

  • First I can use gdk_pixbuf_get_from_surface. It could be easy with that but I just get the picture mapped in the GtkDrawingArea, not the painting made with cairo.
  • Second, gdk_pixbuf_get_from_window. This is the way I choose because I think it fits my needs. Indeed, what I want is just to make a quick snapshot of my drawing area with all labels and painting drawn on the picture.
    My following code works as expected on GNU/Linux, but on Windows that gives me black png. Does someone could help me to fix the issue?
gtk_widget_get_allocation(widget, &allocation_w);
GdkWindow *window = gtk_widget_get_parent_window(widget);
if (window) {
	pixbuf = gdk_pixbuf_get_from_window(window, allocation_w.x, allocation_w.y, allocation_w.width, allocation_w.height);
	file = g_file_new_build_filename(com.wd, filename, NULL);
	g_free(filename);
		if (pixbuf) {
		stream = (GOutputStream*) g_file_replace(file, NULL, FALSE,	G_FILE_CREATE_NONE, NULL, &error);
		if (stream == NULL) {
			if (error != NULL) {
				g_warning("%s\n", error->message);
				g_clear_error(&error);
			}
			g_object_unref(pixbuf);
			g_object_unref(file);
			return;
		}
		gdk_pixbuf_save_to_stream_async(pixbuf, stream, "png", NULL,
				snapshot_callback, (gpointer) g_file_get_basename(file), NULL);

		g_object_unref(stream);
		g_object_unref(pixbuf);
		g_object_unref(file);
	}
}

Is there something wrong in my code/approach?

You typically do not.

The way to do this is to draw on a Cairo image surface, and then use the Cairo surface as the source when drawing the widget; then, you can also get the image data from the image surface.

The API to get a pixbuf from a surface is pretty much a remnant of the time when GTK was X11-only.

Did you mean from the window here ?

Yes, sorry: from a windowing system surface, like a GdkWindow (which is called GdkSurface in GTK4). Back when widgets were backed by an actual windowing system surface you could use platform-specific API to download the pixel data; it’s been a long time since that has been the case—GTK 2.12, or 2007. All the relevant API have either been deprecated, are not portable, or do not exist any more.

The appropriate way to get the pixel data out of a widget is if you draw to a different target, and then use the same target to both draw the contents of a widget, and to get the image data.

1 Like

Please @ebassi is there some example of GtkOffscreenWindow use?
I can’t find any.

I would like to (temporary) move my widget (already attached to a container) to the OffscreenWindow and then get the pixbuf. How I can do it?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.