In this article we will see how to encode an image as a Base64 string in Python.
We can implement the following solution:
import base64
import os
import re
def create_b64_image_data(img_path = None):
if img_path is None:
return ''
if not os.path.exists(img_path):
return ''
if not re.search(r'\.(jpe?g|png|gif)$', img_path):
return ''
with open(img_path, 'rb') as img:
data = base64.b64encode(img.read())
return data.decode()
Before making the conversion we verify that the image exists and is in the desired format. Then we use the b64encode()
method to get a byte buffer and finally we return the corresponding Base64 string with the decode()
method.