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
?
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).
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' ))
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.
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.
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.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With