[Image-SIG] reading image from database

Nils de Reus nils.de.reus at ivm.vu.nl
Tue Apr 6 15:10:49 CEST 2010

When I am getting a binary stored image from a database or as output from another process and I need to dynamically feed it into PIL, I usually resort to StringIO. The charm there is that I can simply use Image.open() and leave the hassle of figuring out the image header to PIL.

import StringIO
import Image


cursor = connection.cursor()
cursor.execute("SELECT file from table")
row = cursor.fetchone()

img_stringio_in = StringIO.StringIO( row[0] )

img_full = Image.open( img_stringio_in )

# You did not specify how you wanted to crop, so I leave defining the box parameter as an exercise to your imagination - but for the example I'll crop to the top-left 100x100 area.

box = ( 0 , 0 , 100 , 100 )

img_cropped = img_full.crop( box )

Now you have a cropped image, and if I understand well, you want to write it back somehow into your database? Several different ways you could proceed now.. you could either dump a raw string with the toString function, or create another StringIO object and specify that as the file to save into using save() or one of the other means of saving the image, and dump that thing back into your database. Remember that if using the StringIO trick, you need to seek() back to the start after saving into it, like this:

img_stringio_out = StringIO.StringIO()
img_cropped.save( img_stringio_out, format="png" )
img_stringio_out.seek( 0 )

Otherwise, a later img_stringio_out.read() would return nothing, since the internal cursor would already be at EOF after the save()

Kind regards,

> I want to use PIL library for crop image on the fly. In my python script:
> cursor = connection.cursor()
> cursor.execute("SELECT file from table");
> row = cursor.fetchone();
> filetype = imghdr.what(0,row[0]);
> mimetype = 'image/' + filetype;
> response = HttpResponse(row[0],mimetype = mimetype );
> How to correct use PIL library for read image to Image object and return image after crop ?
> _______________________________________________
> Image-SIG maillist  -  Image-SIG at python.org
> http://mail.python.org/mailman/listinfo/image-sig

More information about the Image-SIG mailing list