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

How can i open image file after compression in Pillow Python?

尝试在 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

知道如何打开图片吗?

使用 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),你会得到一个错误,因为文件位置在"file"的末尾,那里没有什么可读的。