本文介绍了Python 请求 base64 图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 requests 从远程 URL 获取图像.由于图像始终为 16x16,我想将它们转换为 base64,以便稍后将它们嵌入 HTML img 标记中使用.

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

response 的输出是:

response = b'GIF89ax80x00x80x00xc4x1fx00xffxffxffx00x00x00xffx00x00xffx88x88"""xffff...

HTML 部分是:

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

但是图片没有显示.

如何正确地对 response 进行 base-64 编码?

How can I properly base-64 encode the response?

推荐答案

我认为只是

import base64
import requests

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

假设 content-type 已设置.

这篇关于Python 请求 base64 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 01:03
查看更多