How to open a simple image using streams in Pillow

2019-06-24 10:37发布

from PIL import Image


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

file_path = io.BytesIO();

image.save(file_path,'JPEG');


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

I get this error TypeError: embedded NUL character on the last statement Image.open on running the program

What is the correct way to open a file from streams?

1条回答
三岁会撩人
2楼-- · 2019-06-24 11:33

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

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.

查看更多
登录 后发表回答