我需要将图像(可以是jpg,png等任何类型)转换为JSON可序列化。
我调查了解决方案here,但接受的解决方案有错字,我不确定如何解决。
答案 0 :(得分:1)
这可能会让您入门:
import json
import base64
data = {}
with open('some.gif', mode='rb') as file:
img = file.read()
data['img'] = base64.encodebytes(img).decode("utf-8")
print(json.dumps(data))
答案 1 :(得分:1)
Python 2
由于base64.encodebytes()
已在base64中弃用,因此可以如下修改上述代码段:
import json
import base64
data = {}
with open('some.gif', mode='rb') as file:
img = file.read()
data['img'] = base64.b64encode(img)
print(json.dumps(data))
然后,使用base64.b64decode(data['img'])
进行转换。