PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 29, 2022

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

 July 29, 2022     image, mime-types, python, python-3.x     No comments   

Issue

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?


Solution

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


Answered By - esqew
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing