Python请求base64图像

时间:2015-05-16 20:36:14

标签: python base64 python-requests data-uri

我正在使用requests从远程网址获取图片。由于图片总是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编码

4 个答案:

答案 0 :(得分:12)

我认为这只是

import base64
import requests

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

假设content-type已设定。

答案 1 :(得分:2)

您可以使用base64包。

import requests
import base64

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

答案 2 :(得分:2)

这对我有用:

import base64
import requests

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

答案 3 :(得分:0)

这是我通过 Http 请求发送/接收图像的代码,使用 base64 编码

<块引用>

发送请求:

# 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,
}
<块引用>

接收请求

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

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