ImgClip (xclip for images)



Here is a little python script I wrote to emulate xclip for image files. xclip, if you don't know, is a simple command line tool for setting/retrieving text from the clipboard. For instance the following command

ls -l | xclip -i -selection clipboard

copies the current directory listing to the gnome clipboard, where it can then be ctrl + v pasted into a forum post, email, etc.

I really wanted something that does the same for image files. Unfortunately the following does not work:

cat image.png | xclip -i -selection clipboard

I'm not sure of the details of how the gnome clipboard works… but this doesn't do it. I discovered a way to do it easily using pygtk. Here is a python script that does exactly what I want:

#! /usr/bin/python

import pygtk
pygtk.require('2.0′)
import gtk
import os
import sys

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()


copy_image(sys.argv[1]);

P.S. I pasted this code into this post using the following command

cat imgclip.py | xclip -i -selection clipboard

Make sure to set the script to executable

chmod +x imgclip.py

And then use it like this

./imgclip.py /path/to/some/image.png

Comentarios


Comments powered by Disqus