File size: 2,077 Bytes
a00946c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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