save current window as image using gtk#

2019-01-29 01:07发布

问题:

How can I save the current window as an image file such as a png?

I know I can get a gdkWindow from current windows. I can even get an image. From this image struct I can even query each pixel. But from what I understand what I really need is to get a pixbuf.

int width;
int height;
this.GetSize(width, height);
this.GdkWindow.GetImage(0,0,width,height).?

How do I get a pixbuf from a gtk window or a gdk window or a gdk image ?

EDIT

int width;
int height;
this.GetSize(out width, out height);
Pixbuf pixbuf = Pixbuf.FromDrawable (this.GdkWindow, this.Colormap, 0, 0, 0, 0, width, height);
pixbuf.Save("/tmp/out.png","png");

is kinda working. A png is exported with the correct size but it is blurred.

EDIT 2

The solution is working. The bluriness was a bug of gnome image viewer

回答1:

Use gdk_pixbuf_get_from_drawable to get from the GdkWindow to a GdkPixbuf, then if you want to save to a file use gdk_pixbuf_save.

In Cairo, which is the more future-proof method, you could use cairo_image_surface_create, pass the result to cairo_create, pass that to gdk_cairo_set_source_window, copy to your image surface with cairo_paint, and write your image with cairo_surface_write_to_png.

Also note that your question is similar to this one. However, since the answer to that question does not work, if my answer answers your question, I'll close the other question as a dupe of this.