如何在Python中从StringIO中读取图像到PIL?

12

如何在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

我认为在这里实际上不需要StringIO - 只需使用 im = Image.open("test.gif") - user2629998
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
17

不要使用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

可能是版本更改了,但现在不起作用: $ python Python 3.9.0 (v3.9.0:9cf6752276, Oct 5 2020, 11:29:23) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from io import StringIO >>> from PIL import Image >>> image_file = StringIO(open("t.jpg",'rb').read()) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: initial_value must be str or None, not bytes - russell
2
我发现使用io.BytesIO()代替io.StringIO更加有效。 - russell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,