Skip to content Skip to sidebar Skip to footer

Python Requests Base64 Image

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

Solution 1:

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.


Solution 2:

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"))

Solution 3:

You may use the base64 package.

import requests
import base64

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

Solution 4:

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)

Post a Comment for "Python Requests Base64 Image"