且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Pillow-Python中使用流打开简单的图像

更新时间:2023-10-23 16:33:46

http://effbot.org/imagingbook/introduction.htm#more-on-reading-images

from PIL import Image
import StringIO

buffer = StringIO.StringIO()
buffer.write(open('image.jpeg', 'rb').read())
buffer.seek(0)

image = Image.open(buffer)
print image
# <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=800x600 at 0x7FE2EEE2B098>

# if we try open again
image = Image.open(buffer)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2028, in open
   raise IOError("cannot identify image file")
IOError: cannot identify image file

确保在读取任何StringIO对象之前调用buff.seek(0).否则,您将从缓冲区的末尾读取,缓冲区的末尾看起来像是一个空文件,很可能会引起您所看到的错误.

Make sure you call buff.seek(0) before reading any StringIO objects. Otherwise you'll be reading from the end of the buffer, which will look like an empty file and is likely causing the error you're seeing.