Search code examples
pythonbase64python-requestsdata-uri

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?


Solution

  • 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.