获取内存中的压缩图像字节表示形式 [英] Get compressed image byte representation in memory

查看:72
本文介绍了获取内存中的压缩图像字节表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得与以下相同的效果:

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

无需写入磁盘?

即我想获取压缩图像的字节表示形式,但不必求助于temporary_thumbnail_path. 我知道PIL文档建议使用

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(),带有用于内存中数据的BytesIO参数.

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.

推荐答案

这并不难:

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

这篇关于获取内存中的压缩图像字节表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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