如何在Pillow Python中压缩后打开图像文件?

时间:2015-03-29 12:07:10

标签: python python-imaging-library pillow

尝试在Pillow-PYTHON中打开和压缩图像时

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

fpath = io.BytesIO();
image.save(fpath,'JPEG',dpi=[300,300], quality=image_quality);

compressed_image = Image.open(fpath.getvalue());

打开压缩图像时出现以下错误

TypeError: embedded NUL character

知道如何让图像打开吗?

1 个答案:

答案 0 :(得分:4)

使用BytesIO对象本身:

In [1]: from PIL import Image

In [2]: from io import BytesIO

In [3]: image = Image.open("foo.jpg")

In [4]: fpath = BytesIO()

In [5]: image.save(fpath,'JPEG', dpi=[300, 300], quality=40)

In [6]: fpath.seek(0)
Out[6]: 0

In [7]: compressed_image = Image.open(fpath)

如果您不使用fpath.seek(0),则会收到错误,因为文件位置位于“文件”的末尾,并且没有任何内容可供阅读。