我正在尝试发送包含Pillow图像的json字典作为其中一个字段,为此必须将图像转换为字符串。
我尝试使用Pillow函数:
image.toString()
但仍然得到了字节,所以我尝试对其进行编码:
buff = BytesIO()
image.save(buff, format="JPEG")
img_str = base64.b64encode(buff.getvalue())
但仍然将其作为字节获取。如何将Pillow图像转换为可保存在JSON文件中的格式?
我正在尝试发送包含Pillow图像的json字典作为其中一个字段,为此必须将图像转换为字符串。
我尝试使用Pillow函数:
image.toString()
但仍然得到了字节,所以我尝试对其进行编码:
buff = BytesIO()
image.save(buff, format="JPEG")
img_str = base64.b64encode(buff.getvalue())
但仍然将其作为字节获取。如何将Pillow图像转换为可保存在JSON文件中的格式?
import json
from PIL import Image
import numpy as np
filename = "filename.jpeg"
image = Image.open(filename)
json_data = json.dumps(np.array(image).tolist())
new_image = Image.fromarray(np.array(json.loads(json_data), dtype='uint8'))
b64encode
调用的结果上调用.decode('ascii')
。我同意这会起作用,但我认为一开始进行base64编码引入了不必要的额外步骤,使您的代码更加复杂。image.tostring
返回的字节。唯一的复杂之处在于字节对象可能包含大于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)
(* 但是令我惊讶的是,使用UTF-8编码生成的JSON文件仍然比使用Latin1编码生成的文件要小,至少对于我的示例文件来说。根据自己的判断确定文件大小或程序清晰度哪个更重要。)
tobytes()
而不是 image.save(buff, format="JPEG")
,因为它稍微更加简洁。但这对于我的答案并非必要;无论他们选择使用 b64-和-ascii 编码还是 latin1 编码,OP都应该随意继续使用自己的 BytesIO 策略。 - Kevin
jstr = json.dumps({"image": base64.b64encode(buff.getvalue()).decode('ascii')})
- Mark Setchell