在PIL打开的base64字符串时,奇怪的IOError [英] Strange IOError when opening base64 string in PIL

查看:1216
本文介绍了在PIL打开的base64字符串时,奇怪的IOError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过编码图像,并在Python Shell解码相同。我第一次在PIL开去codeD的base64字符串没有错误,如果我再说一遍,我发现了Image.open()命令的 IO错误:无法识别图像文件

I tried encoding an image and decoding the same in python shell. The first time I open the decoded base64 string in PIL there is no error, if I repeat the Image.open() command I'm getting 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

这是怎么回事?

Why is this happening?

推荐答案

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

When you create your image_string, you're creating a fake file-like object backed by a string. When you call Image.open, it reads this fake file, moving the file pointer to the end of the file. Attempting to use Image.open on it again just gives you an EOF.

您需要或者重新创建你的 StringIO的对象,或求()来流的开始

You need to either re-create your StringIO object, or seek() to the beginning of the stream.

这篇关于在PIL打开的base64字符串时,奇怪的IOError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆