Python requests base64 image

旧街凉风 提交于 2021-02-08 12:21:14

问题


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?


回答1:


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.




回答2:


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



回答3:


You may use the base64 package.

import requests
import base64

response = requests.get(url).content
print(response)
b64response = base64.b64encode(response)
print b64response 


来源:https://stackoverflow.com/questions/30280495/python-requests-base64-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!