convert image in clipboard to data URI

14.02.12

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())
clipboard.set_text(cbText)
clipboard.store()

sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)

textview = gtk.TextView()
textbuffer = textview.get_buffer()
sw.add(textview)
sw.show()
window.add(sw)
textbuffer.set_text(cbText)

window.connect("destroy", gtk.main_quit)
window.show()
textview.show()
gtk.main()



#time.sleep(10)

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.