import os import io import base64 import uuid import logging from PIL import Image # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def encode_image(image_path: str) -> str: """ Convert an image file to a base64 encoded string. Args: image_path (str): The file path to the image. Returns: str: The base64 encoded string of the image. """ try: with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode("utf-8") logger.info(f"Successfully encoded image from {image_path}") return encoded_string except Exception as e: logger.error(f"Error encoding image {image_path}: {e}") raise def decode_image(base64_string: str) -> Image.Image: """ Convert a base64 encoded string to a PIL Image object. Args: base64_string (str): The base64 encoded string. Returns: Image.Image: The decoded PIL Image. """ try: image_data = base64.b64decode(base64_string) image = Image.open(io.BytesIO(image_data)) logger.info("Successfully decoded base64 image string") return image except Exception as e: logger.error(f"Error decoding image: {e}") raise def save_image(image: Image.Image, directory: str = "image_outputs") -> str: """ Save a PIL Image to disk with a unique filename. Args: image (Image.Image): The image to save. directory (str): The directory to save the image in. Defaults to "image_outputs". Returns: str: The file path of the saved image. """ try: os.makedirs(directory, exist_ok=True) image_id = str(uuid.uuid4()) image_path = os.path.join(directory, f"{image_id}.png") image.save(image_path) logger.info(f"Saved image to {image_path}") return image_path except Exception as e: logger.error(f"Error saving image to {directory}: {e}") raise