【问题标题】:Strange IOError when opening base64 string in PIL在 PIL 中打开 base64 字符串时出现奇怪的 IOError
【发布时间】:2013-11-11 16:10:12
【问题描述】:

我尝试在 python shell 中对图像进行编码和解码。我第一次在 PIL 中打开解码的 base64 字符串时没有错误,如果我重复 Image.open() 命令我得到 IOError: cannot identify image file.

>>> with open("/home/home/Desktop/gatherify/1.jpg", "rb") as image_file:
...     encoded_string = base64.b64encode(image_file.read())
>>> image_string = cStringIO.StringIO(base64.b64decode(encoded_string))
>>> img = Image.open(image_string)
>>> img
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=576x353 at 0xA21F20C>
>>> img.show() <-- Image opened without any errors. 
>>> img = Image.open(image_string)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1980, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file

为什么会这样?

【问题讨论】:

    标签: python base64 python-imaging-library ioerror


    【解决方案1】:

    当您创建image_string 时,您正在创建一个由字符串支持的假文件类对象。当您调用Image.open 时,它读取这个假文件,将文件指针移动到文件末尾。再次尝试使用 Image.open 只会给你一个 EOF。

    您需要重新创建您的 StringIO 对象,或者将 seek() 重新创建到流的开头。

    【讨论】:

    • 仅供参考,Image.open 不会读取整个文件(不会将文件指针移动到文件末尾)。它只读取文件头。见Image.open
    • stackoverflow.com/questions/19908975/…看看能不能解决这个问题,和这个问题有关
    • 我不知道@falsetru,谢谢。延迟加载是有意义的,尤其是在处理大图像时(想想 1GB+ NASA 图像)
    • 对不起,在上一条评论中添加了错误的链接。见Image.open
    【解决方案2】:

    image_string 是类文件对象。类文件对象具有文件位置。

    一旦文件被读取,位置就前进了。

    除非您使用seek 方法明确定位它,否则任何后续操作都会在该位置发生。

    所以如果你想重新打开文件:

    ...
    image_string.seek(0) # reset file position to the beginning of the file.
    img = Image.open(image_string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2021-11-19
      • 2011-02-06
      • 1970-01-01
      • 2011-01-16
      相关资源
      最近更新 更多