字符串格式化为base64到base64对象

时间:2018-06-11 13:37:15

标签: python json python-3.x

从帖子请求中,我收到了一个JSON的base64。问题是我不能将文件类型从字符串更改为base64,因为它已经格式化为base64。需要base64将其转换回图像。

json_data = request.get_json(force=True)
img = json_data['img']
print(img)
with open("imageToSave.png", "wb") as fh:
   fh.write(base64.decodebytes(img))

1 个答案:

答案 0 :(得分:2)

为了解码它,添加第三行将字符串解码为base64

json_data = request.get_json(force=True)
img = json_data['img']
imgdata = base64.b64decode(img)
filename = 'upload/newimg.jpg'  # I assume you have a way of picking unique filenames
    with open(filename, 'wb') as f:
        f.write(imgdata)