convert image in clipboard to data URI


There are many times that I just want to paste an image in a webpage. So I wrote this script that gets the image from the clipboard, converts it to a data URI and copies it again. The problem is, on ubuntu, when python quits it takes the clipboard with it to oblivion. So I had to open a window so that the clipboard doesn't empty. It's not pretty, but it works, and as a bonus you have the window with the data there to reuse. (triple click the window contents to select all)

#! /usr/bin/python

import pygtk
import gtk
import os
import sys
import base64
import cStringIO
import time

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
clipboard = gtk.clipboard_get()
cbImage = clipboard.wait_for_image()
fH = cStringIO.StringIO() 
cbImage.save_to_callback(fH.write, "png") 
cbText = "data:image/png;base64," + base64.b64encode(fH.getvalue())

sw = gtk.ScrolledWindow()

textview = gtk.TextView()
textbuffer = textview.get_buffer()

window.connect("destroy", gtk.main_quit)


In plain english, if you want to paste an image in a post on your favorite forum, copy it, double click the icon of my little app, and then paste it where the image url would be.