Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests base64 image

I am using requests to get the image from remote URL. Since the images will always be 16x16, I want to convert them to base64, so that I can embed them later to use in HTML img tag.

import requests
import base64
response = requests.get(url).content
print(response)
b = base64.b64encode(response)
src = "data:image/png;base64," + b

The output for response is:

response = b'GIF89a\x80\x00\x80\x00\xc4\x1f\x00\xff\xff\xff\x00\x00\x00\xff\x00\x00\xff\x88\x88"""\xffff\...

The HTML part is:

<img src="{{src}}"/>

But the image is not displayed.

How can I properly base-64 encode the response?

like image 759
nickbusted Avatar asked May 16 '15 20:05

nickbusted


People also ask

How to convert Base64 string to image in Python?

The following steps give the working of the above code to convert the base64 string to Image in Python: Then open the file which contains base64 string data for an image. We do this using the open () function in python. The open () function takes two parameters-the file to be opened and the mode. In our case, the mode is ‘rb’ (read binary).

How to remove B’ from the prefix of base64 code in Python?

Or you can say your base64 encoded string is in the pair of single quotation. To remove b’ from the prefix of base64 code in Python, you can use string.encode (‘utf-8’) method. import base64 with open ( "grayimage.png", "rb") as img_file: b64_string = base64.b64encode (img_file.read ()) print (b64_string.decode ( 'utf-8' ))

Why should I encode my images in base64?

When you encode your images in Base64, your images can be transferred and saved as text. Although there will be a 37% bloat in space requirements, it can be useful to encode images in Base64.

How do I convert an image to a string in Python?

Convert Image to Base64 String in Python To convert the Image to Base64 String in Python, we have to use the Python base64 module that provides b64encode () method. Python base64.b64encode () function encodes a string using Base64 and returns that string.


2 Answers

I think it's just

import base64
import requests

response = requests.get(url)
uri = ("data:" + 
       response.headers['Content-Type'] + ";" +
       "base64," + base64.b64encode(response.content))

Assuming content-type is set.

like image 103
David Ehrmann Avatar answered Oct 06 '22 04:10

David Ehrmann


This worked for me:

import base64
import requests

response = requests.get(url)
uri = ("data:" + 
       response.headers['Content-Type'] + ";" +
       "base64," + base64.b64encode(response.content).decode("utf-8"))
like image 36
spedy Avatar answered Oct 06 '22 03:10

spedy