PyCairo, PIL and StringIO

Fredrik Lundh fredrik at
Wed Jan 2 15:39:11 CET 2008

Jair Trejo wrote:

> I'm doing some image processing in PIL, and I want to
> display the results in a GTK window using PyCairo, so
> I create a Cairo image surface from the PIL Image like
> this:
> data
>         mfile = StringIO.StringIO()
>, format="PNG")
>         ima =
> cairo.ImageSurface.create_from_png(mfile)
>         mfile.close()
>         return ima
> Where final is a PIL image. The problem is, I get a
> IOError: error while reading from Input Stream.
> ¿Any idea of why is this happening?

"save" leaves the file pointer at an undefined position (usually at the 
end), so my guess is that you have to rewind the file before you pass it
to the next function:, format="PNG") # rewind

also note that compressing and decompressing will introduce unnecessary 
overhead; chances are that you might get a lot better performance if you 
just shuffle the raw pixels.  I haven't used PyCairo myself, but from a 
quick look at the ImageSurface documentation, something like this should 
work (untested):

    if final.mode != "RGB":
        final = final.convert("RGB")
    w, h = final.size
    data = final.tostring() # get packed RGB buffer
    ima = cairo.ImageSurface.create(data, FORMAT_RGB24, w, h, w*3)

(tweak as necessary)


More information about the Python-list mailing list