Here is my function to convert PIL image into base64:
# input: single PIL image
def image_to_base64(self, image):
output_buffer = BytesIO()
now_time = time.time()
image.save(output_buffer, format='PNG')
print('--image.save:' + str(time.time()-now_time))
now_time = time.time()
byte_data = output_buffer.getvalue()
print('--output_buffer.getvalue:' + str(time.time()-now_time))
now_time = time.time()
encoded_input_string = base64.b64encode(byte_data)
print('--base64.b64encode:' + str(time.time()-now_time))
now_time = time.time()
input_string = encoded_input_string.decode("utf-8")
print('--encoded_input_string.decode:' + str(time.time()-now_time))
return input_string
My output:
--image.save:1.05138802528
--output_buffer.getvalue:0.000611066818237
--base64.b64encode:0.01047706604
--encoded_input_string.decode:0.0172328948975
As we can see, the function is pathetically slow. How can we improve this?
[Edit]
Ok! Here is the full example
import time
import requests
import base64
from PIL import Image
from io import BytesIO
# input: single PIL image
def image_to_base64(image):
output_buffer = BytesIO()
now_time = time.time()
image.save(output_buffer, format='PNG')
print('--image.save:' + str(time.time()-now_time))
now_time = time.time()
byte_data = output_buffer.getvalue()
print('--output_buffer.getvalue:' + str(time.time()-now_time))
now_time = time.time()
encoded_input_string = base64.b64encode(byte_data)
print('--base64.b64encode:' + str(time.time()-now_time))
now_time = time.time()
input_string = encoded_input_string.decode("utf-8")
print('--encoded_input_string.decode:' + str(time.time()-now_time))
return input_string
img_url = "https://www.cityscapes-dataset.com/wordpress/wp-content/uploads/2015/07/stuttgart03.png"
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
input_string = image_to_base64(img)
The bottleneck here is
image.save(output_buffer, format='PNG')
which transform the PIL image into byte. I think it would be nice if I can speed up this step.