如何在PillowPython中使用流打开一个简单的图像

2024-04-20 02:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

from PIL import Image


image = Image.open("image.jpg")

file_path = io.BytesIO();

image.save(file_path,'JPEG');


image2 = Image.open(file_path.getvalue());

我在运行程序的最后一个语句Image.open上得到这个错误TypeError: embedded NUL character

从流中打开文件的正确方法是什么?在


Tags: pathfromioimageimportpilsaveopen
1条回答
网友
1楼 · 发布于 2024-04-20 02:33:48

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

一定要打电话buff.seek搜索(0)在读取任何StringIO对象之前。否则,您将从缓冲区的末尾进行读取,这看起来像一个空文件,很可能导致您看到的错误。在

相关问题 更多 >