【问题标题】:Python requests base64 imagePython 请求 base64 图像
【发布时间】:2015-05-16 20:36:13
【问题描述】:

我正在使用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 编码?

【问题讨论】:

  • 你的问题是什么?
  • 我认为它是“我有一个str (其中包含图像数据,但这并不重要)。我如何对它进行base-64编码,以便我可以构建一个数据URI来自它?”

标签: python base64 python-requests data-uri


【解决方案1】:

我觉得只是

import base64
import requests

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

假设 content-type 已设置。

【讨论】:

  • 这按预期工作!我只需要将base64.b64encode(response.content)) 更改为str(base64.b64encode(r.content).decode("utf-8")))。谢谢!
  • 我真的很惊讶您必须这样做,但是您从 b64encode() 之类的函数返回的类型以及 urllib 采用的类型可能会让您感到惊讶。另外,这是 Python 3 吗?
【解决方案2】:

这对我有用:

import base64
import requests

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

【讨论】:

    【解决方案3】:

    您可以使用 base64 包。

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

    【讨论】:

      【解决方案4】:

      这是我通过 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)
      

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多