开发者

Copying image to clipboard in python in linux

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 o开发者_如何学Pythonther options are there? What does ubuntu use ?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜