如何在python中将StringIO中的图像读入PIL

时间:2014-03-18 00:23:25

标签: python python-imaging-library

如何在python中将StringIO中的图像读入PIL?我将有一个stringIO对象。如何从中读取图像?我无法从文件中读取图像。哇!

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

1 个答案:

答案 0 :(得分:14)

不要使用readlines(),它会返回一个不是你想要的字符串列表。要从文件中检索字节,请改用read()函数。

您的示例在我的电脑上开箱即用read()JPG文件:

# Python 2.x
>>>from StringIO import StringIO
# Python 3.x
>>>from io 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