简体   繁体   中英

How to get an image from an API response with content type "mime: image/jpg" in Python?

I did a request to an API and obtain characters from an image. I want to put those characters into a 'jpg' file to be able to visualize the image. The content-type is 'mime: image/jpg' and the data is the following one (it's not the complete one because it would be too much):

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/wAALCAMABAABAREA/8QAGwABAAMBAQEBAAAAAAAAAAAAAAQFBgMHAgj/xAA4EAABBAIBAwIFAwMCBwEBAQEAAQIDBAUREgYTIRQiFRYxMkEHIzMlUWI0QkZhZXGhoqOBF1Ik/9oACAEBAAA/APyoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2DM9K4NnTcmRdia1KovT8N/1MFmV0jLsjkRkfB0jv23LtNq3+/uTXjMZH9Mc9Qo3LEyQrJTr+qniRkqcWoiK5EkViROc1F8o16/Rdb0S

How can I do it?

A quick bit of research indicates /9j/ is a magic number likely indicating the binary representation of a JPEG file that's been Base64-encoded. ( Source ).

Thus it should be possible to use the base64 module in Python to generate the file you describe:

import base64
jpg_b64_string_data = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/wAALCAMABAABAREA/8QAGwABAAMBAQEBAAAAAAAAAAAAAAQFBgMHAgj/xAA4EAABBAIBAwIFAwMCBwEBAQEAAQIDBAUREgYTIRQiFRYxMkEHIzMlUWI0QkZhZXGhoqOBF1Ik/9oACAEBAAA/APyoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2DM9K4NnTcmRdia1KovT8N/1MFmV0jLsjkRkfB0jv23LtNq3+/uTXjMZH9Mc9Qo3LEyQrJTr+qniRkqcWoiK5EkViROc1F8o16/Rdb0S"
image_data = base64.decodestring(jpg_b64_string_data)
f = open("image.jpg", "w")
f.write(image_data)
f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM