Python 请求 base64 图片

Python requests base64 image

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

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

response 的输出是:

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

HTML部分是:

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

但是没有显示图片

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

我觉得只是

import base64
import requests

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

假设设置了 content-type

您可以使用base64包。

import requests
import base64

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

这对我有用:

import base64
import requests

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

这是我通过 Http 请求 send/receive 图片的代码,使用 base64

编码

Send Request:

# Read Image
image_data = cv2.imread(image_path)
# Convert numpy array To PIL image
pil_detection_img = Image.fromarray(cv2.cvtColor(img_detections, cv2.COLOR_BGR2RGB))

# Convert PIL image to bytes
buffered_detection = BytesIO()

# Save Buffered Bytes
pil_detection_img.save(buffered_detection, format='PNG')

# Base 64 encode bytes data
# result : bytes
base64_detection = base64.b64encode(buffered_detection.getvalue())

# Decode this bytes to text
# result : string (utf-8)
base64_detection = base64_detection.decode('utf-8')
base64_plate = base64_plate.decode('utf-8')

data = {
    "cam_id": "10415",
    "detecion_image": base64_detection,
}

Recieve Request

content = request.json
encoded_image = content['image']
decoded_image = base64.b64decode(encoded_image)

out_image = open('image_name', 'wb')
out_image.write(decoded_image)