如何在Pillow-Python中使用流打开简单的图像 [英] How to open a simple image using streams in Pillow-Python

查看:284
本文介绍了如何在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

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?

推荐答案

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.

这篇关于如何在Pillow-Python中使用流打开简单的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆