Get compressed image byte representation in memory

2019-07-29 09:25发布

How can I get the same effect as:

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()

without having to write to disk ?

i.e. I would like to get the bytes representation of the compressed image, but without having to resort to temporary_thumbnail_path. I know that PIL documentation recommends using

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

but I am not sure to understand what this means and haven't found examples online.

1条回答
姐就是有狂的资本
2楼-- · 2019-07-29 10:14

It was not so hard:

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()
查看更多
登录 后发表回答