我正在尝试发送应该包含枕头图像作为他的字段之一的 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/