0

I have a snapshot tool in linux, i copied the image there into clipboard

now i want to save. I am not able to understand how to complete the steps. I wrote what i can understand till

I want to do it using pyObject

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

after this how to save image to /home/user/filename.png

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

1

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))
kW90
  • 11
  • 1