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

How to open a simple image using streams in Pillow-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

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

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

使用BytesIO要简单得多,我花了一段时间才弄明白。例如,这允许您读取和写入 zip 文件。

from PIL import Image
from io import BytesIO

# bytes of a simple 2x2 gif file
gif_bytes = b'\x47\x49\x46\x38\x39\x61\x02\x00\x02\x00\x80\x00\x00\x00\xFF\xFF\xFF\x21\xF9\x04\x00\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x02\x00\x02\x00\x00\x02\x03\x44\x02\x05\x00\x3B'
gif_bytes_io = BytesIO() # or io.BytesIO()

# store the gif bytes to the IO and open as image
gif_bytes_io.write(gif_bytes)
image = Image.open(gif_bytes_io)

# optional proof of concept:
# image.show()

# save as png through a stream
png_bytes_io = BytesIO() # or io.BytesIO()
image.save(png_bytes_io, format='PNG')
print(png_bytes_io.getvalue()) # outputs the byte stream of the png