File size: 1,309 Bytes
04ffb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import io
import base64
import uuid
from PIL import Image
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def encode_image(image_path: str) -> str:
    """Convert an image file to base64 string."""
    try:
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode("utf-8")
    except Exception as e:
        logger.error(f"Error encoding image: {str(e)}")
        raise

def decode_image(base64_string: str) -> Image.Image:
    """Convert a base64 string to a PIL Image."""
    try:
        image_data = base64.b64decode(base64_string)
        return Image.open(io.BytesIO(image_data))
    except Exception as e:
        logger.error(f"Error decoding image: {str(e)}")
        raise

def save_image(image: Image.Image, directory: str = "image_outputs") -> str:
    """Save a PIL Image to disk and return the path."""
    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"Image saved to {image_path}")
        return image_path
    except Exception as e:
        logger.error(f"Error saving image: {str(e)}")
        raise