这是我将PIL图像转换为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
我的输出:
-image.save:1.05138802528
-output_buffer.getvalue:0.000611066818237
-base64.b64编码:0.01047706604
-encoded_input_string.decode:0.0172328948975
如我们所见,该函数在速度上很慢。我们该如何改善呢?
[编辑]
好!这是完整的示例
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)
这里的瓶颈是
image.save(output_buffer,format='PNG')
将PIL图像转换为字节。我认为如果可以加快这一步会很好。