获取内存中的压缩图像字节表示

Get compressed image byte representation in memory

我怎样才能得到与以下相同的效果:

from PIL import Image
with Image.open(image_path) as image:
  image.thumbnail((200, 200), Image.ANTIALIAS)
  image.save(temporary_thumbnail_path)
with open(temporary_thumbnail_path, "rb") as thumbnail_file:
  thumbnail_as_string = base64.b64encode(thumbnail_file.read()).decode()

无需写入磁盘?

即我想获得 compressed 图像的字节表示,但不必求助于 temporary_thumbnail_path。 我知道 PIL 文档建议使用

save(), with a BytesIO parameter for in-memory data.

但我不确定这意味着什么,也没有在网上找到示例。

没那么难:

import io
from PIL import Image

output = io.BytesIO()
with Image.open(image_path) as image:
  image.thumbnail((400, 400), Image.ANTIALIAS)
  image.save(output, format="JPEG")
  thumbnail_as_string = base64.b64encode(output.getvalue()).decode()