Python: codificare un'immagine come stringa Base64

Python: codificare un'immagine come stringa Base64

In questo articolo vedremo come codificare un'immagine come stringa Base64 in Python.

Possiamo implementare la seguente soluzione:

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

Prima di effettuare la conversione verifichiamo che l'immagine esista e sia nel formato desiderato. Quindi usiamo il metodo b64encode() per ottenere un buffer di byte ed infine restituiamo la stringa corrispondente in Base64 con il metodo decode().

Torna su