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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#! /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
  1. #1 by Kyle on October 31, 2013 - 11:53 pm

    Well this doesn’t work either, as when the script terminates it takes the clipboard with it.

    • #2 by cheshirekow on November 1, 2013 - 4:33 pm

      The script still works on ubuntu 13.04. The GTK clipboard exists outside of the application state so the script shouldn’t take the clipboard with it when it terminates.

(will not be published)