Python-将图像转换为JSON

时间:2019-02-13 00:38:06

标签: json

我需要将图像(可以是jpg,png等任何类型)转换为JSON可序列化。

我调查了解决方案here,但接受的解决方案有错字,我不确定如何解决。

2 个答案:

答案 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'])进行转换。