20

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?

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
nickbusted
  • 1,029
  • 4
  • 18
  • 30

4 Answers4

21

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.

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
  • 10
    This works as expected! I only needed to change `base64.b64encode(response.content))` to `str(base64.b64encode(r.content).decode("utf-8")))`. Thank you! – nickbusted May 16 '15 at 21:09
  • I'm really surprised you had to do that, but the types you get back from functions like `b64encode()` and the types urllib takes can surprise you. Also, is this Python 3? – David Ehrmann May 16 '15 at 21:15
6

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"))
spedy
  • 2,200
  • 25
  • 26
2

You may use the base64 package.

import requests
import base64

response = requests.get(url).content
print(response)
b64response = base64.b64encode(response)
print b64response 
Nipun Talukdar
  • 4,975
  • 6
  • 30
  • 42
0

Here's my code to send/receive images over Http requests, encoded with 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)
Baher El Naggar
  • 181
  • 1
  • 5