在json中保存PIL图像的最佳方法是什么 [英] what is the best way to save PIL image in json
问题描述
我正在尝试发送应该包含 Pillow 图像作为他的字段之一的 json dict,为此我必须将图像转换为字符串.我尝试使用枕头功能:image.toString()
但仍然以字节的形式得到它,所以我尝试对其进行编码:
I'm trying to send json dict that should contain Pillow image as one of his fields, to do that I have to convert the image to string.
I tried to use pillow function:
image.toString()
but still got it as bytes, so I tried to encode it:
buff = BytesIO()
image.save(buff, format="JPEG")
img_str = base64.b64encode(buff.getvalue())
但仍然以字节的形式得到它.如何将 Pillow 图像转换为可以保存在 json 文件中的格式?
but still got it as bytes. How can I convert Pillow images to format that can be saved in json file?
推荐答案
在评论中,Mark Setchell 建议对 b64encode
的结果调用 .decode('ascii')
代码>调用.我同意这会起作用,但我认为 base64encoding 开始引入了一个不必要的额外步骤,使您的代码复杂化.*
In the comments, Mark Setchell suggests calling .decode('ascii')
on the result of your b64encode
call. I agree that this will work, but I think base64encoding to begin with is introducing an unnecessary extra step that complicates your code.*
相反,我建议直接解码 image.tostring
返回的字节.唯一的复杂之处是字节对象可以包含大于 128 的值,因此您无法使用 ascii
对其进行解码.尝试使用可以处理高达 256 的值的编码,例如 latin1
.
Instead, I suggest directly decoding the bytes returned by image.tostring
. The only complication is that the bytes object can contain values larger than 128, so you can't decode it with ascii
. Try using an encoding that can handle values up to 256, such as 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 编码制作的文件小,至少对于我的示例文件.使用您自己的判断来确定文件大小或程序清晰度是否更重要.)
(*but, to my surprise, the resulting json file is still smaller than one made with a latin1 encoding, at least for my sample file. Use your own judgement to determine whether file size or program clarity is more important.)
这篇关于在json中保存PIL图像的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!