[pygtk] PIL and gtk.gdk.Pixbuf

Sebastian Wilhelmi seppi at seppi.de
Wed Jun 4 10:40:14 WST 2003


Hi,

I want to display images from the PIL (Python Imaging Library) in GTK+.
To get them into a gtk.gdk.Pixbuf I wrote the following function. It
might be worth to be added to the FAQ.

-----------------------------------------------------
import pygtk
pygtk.require("2.0")
import gtk

import StringIO
import Image

def Image_to_GdkPixbuf (image):
    file = StringIO.StringIO ()
    image.save (file, 'ppm')
    contents = file.getvalue()
    file.close ()
    loader = gtk.gdk.PixbufLoader ('pnm')
    loader.write (contents, len (contents))
    pixbuf = loader.get_pixbuf ()
    loader.close ()
    return pixbuf
-----------------------------------------------------

Before you ask: StringIO here is faster than cStringIO in my
measurements. Also using ppm/pnm is faster than jpeg (which also would
lose information) or png.

Going the other way round (Pixbuf to Image) would probably involve
writing out a temporary, because there is no way to save a Pixbuf into a
buffer (is there?). Also this direction is not so important, beacuse
most of the time you do all your image processing inside PIL and only
display images with GdkPixbuf.

Bye,
Sebastian
-- 
Sebastian Wilhelmi                 |            här ovanför alla molnen
mailto:seppi at seppi.de              |     är himmlen så förunderligt blå
http://seppi.de



More information about the pygtk mailing list