Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying image to clipboard in python in linux

Tags:

python

copy

image

Ive tried the gtk method, but it is very slow and doesn't work for a 'large' image (120 kb)

import pygtk
pygtk.require('2.0')
import gtk
import os
def copy_image(f):
    assert os.path.exists(f), "file does not exist"
    clipboard = gtk.clipboard_get()
    img = gtk.Image()
    img.set_from_file(f)
    clipboard.set_image(img.get_pixbuf())
    clipboard.store()

Ive tried xclip and it only does text, so what other options are there? What does ubuntu use ?

like image 973
josh Avatar asked Mar 20 '26 10:03

josh


2 Answers

One way of getting text from/to the clipboard is using XSel. It's not pretty and requires you to communicate with an external program. But it works and is quite fast.

Not sure if it's the best solution but I know it works :)

[edit]You're right, it seems that xsel does not support images.

In that case, how about a slightly modified GTK version.

def copy_image(f):
    assert os.path.exists(f), "file does not exist"
    image = gtk.gdk.pixbuf_new_from_file(f)

    clipboard = gtk.clipboard_get()
    clipboard.set_image(image)
    clipboard.store()

Do note that you might have to change the owner if your program exits right away because of how X keeps track of the clipboard.

like image 119
Wolph Avatar answered Mar 23 '26 01:03

Wolph


You might want to use the set_with_data method instead, but that's slightly more work (the image data is only sent when an application requests it, so it needs callback-functions). This has also advantages when you paste in the same application instead of to another application.

like image 35
JanC Avatar answered Mar 23 '26 00:03

JanC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!