python - 在 json 中保存 PIL 图像的最佳方法是什么

标签 python json python-imaging-library

我正在尝试发送应该包含枕头图像作为他的字段之一的 json dict,为此我必须将图像转换为字符串。 我尝试使用枕头功能: image.toString() 但仍然以字节形式得到它,所以我尝试对其进行编码:

buff = BytesIO()
image.save(buff, format="JPEG")
img_str = base64.b64encode(buff.getvalue())

但仍然以字节形式获取它。 如何将 Pillow 图像转换为可以保存在 json 文件中的格式?

最佳答案

在评论中,Mark Setchell 建议对 b64encode 调用的结果调用 .decode('ascii')。我同意这会起作用,但我认为 base64encoding 开始时引入了一个不必要的额外步骤,这会使您的代码复杂化。*

相反,我建议直接解码 image.tostring 返回的字节。唯一的问题是 bytes 对象可以包含大于 128 的值,因此您不能使用 ascii 对其进行解码。尝试使用可以处理最多 256 个值的编码,例如 latin1

from PIL import Image
import json

#create sample file. You don't have to do this in your real code.
img = Image.new("RGB", (10,10), "red")

#decode.
s = img.tobytes().decode("latin1")

#serialize.
with open("outputfile.json", "w") as file:
    json.dump(s, file)

(*但是,令我惊讶的是,生成的 json 文件仍然小于使用 latin1 编码生成的文件,至少对于我的示例文件而言是这样。请自行判断文件大小或程序清晰度哪个更重要。)

关于python - 在 json 中保存 PIL 图像的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56428037/

相关文章:

Python:导入问题

python - 您可以对多个对象使用枚举吗?

Python 2 与 Python 3 导入

python - 在 python 中导入模块时是否有类似于 `return` 的情况?

python - python中的try语句放在哪里

json - 使用Elasticsearch Nest客户端和Utf8Json序列化器时如何捕获与任何POCO属性都不匹配的JSON数据的剩余部分

python - python 只获取元素数组中元素的一个值

javascript - 检查 JSON 对象中是否存在日期

python - PIL : ImportError: The _imaging extension was built for another version of pillow or PIL

python - PIL 无法识别 Mac OS 下的 jpeg 库