PyCairo, PIL and StringIO

Fredrik Lundh fredrik at pythonware.com
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()
>         final.save(mfile, 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:

     final.save(mfile, format="PNG")
     mfile.seek(0) # 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)

</F>




More information about the Python-list mailing list