在PIL中打开base64字符串时出现奇怪的IOError
问题内容:
我尝试在python
shell中对图像进行编码和解码。我第一次在PIL中打开解码的base64字符串时,没有错误,如果我重复执行Image.open()命令,我将得到
IOError:无法识别图像文件。
>>> 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
为什么会这样呢?
问题答案:
创建时image_string
,您正在创建一个由字符串支持的假文件状对象。当您调用时Image.open
,它将 读取
该伪造文件,并将文件指针移到文件末尾。Image.open
再次尝试使用它只会给您带来EOF。
您需要重新创建StringIO
对象,或重新创建seek()
流的开头。