Python - 将图像转换为JSON

14

我需要将一张图片(可以是任何类型,如jpg、png等)转换为可序列化的JSON格式。

我查看了这里的解决方案(链接),但被接受的方案有一个拼写错误,我不确定该如何解决它。

2个回答

26

这可能会帮助您入门:

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))

6

Python 2

由于base64中的base64.encodebytes()已经被弃用,因此可以按照以下方式修改上述代码片段:

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'])将其转换回来。


5
你的标题是不是应该写成“Python 3”? - Chris Fonnesbeck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接