How to read image from StringIO to PIL in python

How to read image from StringIO to PIL in python? I will have a stringIO object. How did I read from him with the image in it? The can not event does not read the image from the file. Wow!

from StringIO import StringIO from PIL import Image image_file = StringIO(open("test.gif",'rb').readlines()) im = Image.open(image_file) print im.format, "%dx%d" % im.size, im.mode Traceback (most recent call last): File "/home/ubuntu/workspace/receipt/imap_poller.py", line 22, in <module> im = Image.open(image_file) File "/usr/local/lib/python2.7/dist-packages/Pillow-2.3.1-py2.7-linux-x86_64.egg/PIL/Image.py", line 2028, in open raise IOError("cannot identify image file") IOError: cannot identify image file 
+8
python python-imaging-library
source share
1 answer

Do not use readlines() , it returns a list of lines, which is not what you want. To extract bytes from a file, use read() instead.

Your example worked out of the box with read() and JPG files on my PC:

 >>>from StringIO import StringIO >>>from PIL import Image >>>image_file = StringIO(open("test.jpg",'rb').read()) >>>im = Image.open(image_file) >>>print im.size, im.mode (2121, 3508) RGB 
+13
source share

All Articles