gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:00:25 25 4
gpt4 key购买 nike

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

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

最佳答案

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)。否则,您将从缓冲区的末尾开始读取,这看起来像一个空文件,很可能会导致您看到的错误。

关于python - 如何在 Pillow-Python 中使用流打开一个简单的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29330570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com