Krishna Kalyan
Krishna Kalyan

Reputation: 1702

Saving a json request as an Image in Flask

I have a flask get request like this

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,...]}

My image file is with the key data.

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

I am unable to save it as a jpeg file.

I am not sure how to decode this object as an image as its currently a list.

Upvotes: 0

Views: 343

Answers (1)

lospejos
lospejos

Reputation: 1986

If I correctly understood your question, it could be done like this:

#!/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

Code of course is not perfect and could be used as starting point.

Upvotes: 1

Related Questions