import time from functools import wraps import base64 from io import BytesIO def timing_decorator(func): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time = end_time - start_time print(f"Function {func.__name__} took {execution_time:.4f} seconds to execute.") return result return wrapper def pil_image_to_base64_url(image, format='JPEG'): """ Convert a PIL image to a Base64-encoded URL. :param image: PIL image object :param format: Image format (default is JPEG) :return: Base64 URL string """ # Create a BytesIO object to hold the image in memory buffered = BytesIO() # Save the image in the provided format (e.g., JPEG or PNG) image.save(buffered, format=format) # Get the base64 encoded string img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") # Create the Base64 URL string base64_url = f"data:image/{format.lower()};base64,{img_str}" return base64_url def pil_image_to_data_url(pil_image): # Convert the image to RGB mode if it's not already if pil_image.mode != 'RGB': pil_image = pil_image.convert('RGB') # Create a BytesIO object to store the image data buffered = BytesIO() # Save the image as JPEG to the BytesIO object pil_image.save(buffered, format="JPEG") # Encode the image data as base64 img_str = base64.b64encode(buffered.getvalue()).decode() # Create the data URL data_url = f"data:image/jpeg;base64,{img_str}" return data_url