且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在json中保存PIL图像的***方法是什么

更新时间:2022-12-18 08:58:27

在评论中,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.)