[reportlab-users] Still confused about PIL Image objects

Sam Hunter shunter at dbsupply.com
Wed May 11 12:10:01 EDT 2005

Hey Ian, I had the same problem and it was a serious pain.  I finally 
just re-wrote some of the Reportlab code so that it could handle PIL 
images passed directly into the canvas.drawImage() function.  I can send 
you the three files I had to change if you like. 

The other option is to use StringIO, save the PIL image to a StringIO 
object, and then pass that in to canvas.drawImage() or make an 
ImageReader object with it.  I forget which works in the non-modified 
version.  The funny part about all of this is that if you are using 
ImageReader it defaults to opening anything without a JPEG extension 
with PIL, and the comments in the JPEG code suggest that PIL should be 
used for that too.

StringIO is kinda funny..  as far as I can tell, you can create either a 
readable, or a writable object, but one object doesn't seem to do both?  
Perhaps I'm confused here....  But I think the code below should work.


The StringIO option goes something like this:
Im = Image.open("imagefile.jpg")
#do some operations on the image......

#then convert to a StringIO object

from cStringIO import StringIO  # "cStringIO" is faster, but if you need 
to subclass, use "StringIO"
writeSIO = StringIO()  #create an empty writeable StringIO object

Im.save(writeSIO, format="JPEG")

readSIO = writeSIO.getvalue()   #create a readable StringIO object

ir = ImageReader(readSIO)

canvas.drawImage(ir, x, y, xsize, ysize)

Ian Sparks wrote:

>It used to be that PIL Image objects could be passed to the canvas.drawImage() method. Then there was a change in ReportLab which made this fail with an error related to "getRGBData()".
>I understand that this was done to reduce the requirement to have PIL installed. Fair enough.
>I'm using reportlab 1.20. I have a PIL Image object that I want to pass to canvas.drawImage(). I'm using PIL because I often need to resize or modify the image in some way before I write it into the PDF.
>Right now I'm doing this :
>		#im is the PIL Image object
>            filename = 'temp_im.bmp'
>            im.save(filename) #This is an annoying hack, save to a file to get it re-imported  
>            canvas.drawImage(filename,....)
>            os.remove(filename) #Remove it again
>There has to be a better way. Someone please enlighten me?
>reportlab-users mailing list
>reportlab-users at reportlab.com

More information about the reportlab-users mailing list