As discussed in this post on SO, the call to Gtk.Clipboard.get()
requires an argument to identify the clipboard. Therefore, to get an image from the clipboard, you'd have to call wait_for_image()
. This will return a pixbuf object.
In order to save this pixbuf object as a .png
to disk, you could convert it to a Pillow image object using the pixbuf2image(pix)
function that was taken from this GitHub Gist from user mozbugbox. The Pillow image object then has a save()
method to save the image directly to disk.
import gi
from PIL import Image as PILImage
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
def pixbuf2image(pix):
"""Convert gdkpixbuf to PIL image"""
data = pix.get_pixels()
w = pix.props.width
h = pix.props.height
stride = pix.props.rowstride
mode = "RGB"
if pix.props.has_alpha == True:
mode = "RGBA"
im = PILImage.frombytes(mode, (w, h), data, "raw", mode, stride)
return im
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
pixbuf_img = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).wait_for_image()
pil_image = pixbuf2image(pixbuf_img)
pil_image.save(str(imgpath))