将json请求保存为Flask中的图像

时间:2017-12-09 11:41:53

标签: python

我有一个像这样的烧瓶获取请求

content = {"vname":"","myPhoto":{"fieldname":"myPhoto","originalname":"flower-purple-lical-blosso.jpg","encoding":"7bit","mimetype":"image/jpeg","buffer":{"type":"Buffer","data":[255,216,255,224,0,...]}

我的图片文件使用密钥data

data = content['myphoto']['buffer']['data']

我无法将其另存为jpeg文件。

我不确定如何将此对象解码为图像,因为它当前是一个列表。

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,可以这样做:

#!/usr/bin/env python3

content = {"vname":"","myPhoto":{"fieldname":"myPhoto","originalname":"flower-purple-lical-blosso.jpg","encoding":"7bit","mimetype":"image/jpeg","buffer":{"type":"Buffer","data":[255,216,255,224,0,20]}}}
data = content['myPhoto']['buffer']['data']
str_data = ''.join(chr(d) for d in data) # build string using list comprehension
bytes_data = str_data.encode() # build bytes array from string
with open('output.jpg', 'wb') as f: # open file for writing bytes
    f.write(bytes_data) # write bytes array to file

当然,代码并不完美,可以作为起点。