File size: 858 Bytes
d61265e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import base64
import io
import os
import uuid
from PIL import Image

def decode_image(image_base64: str) -> Image.Image:
    """Decodes a base64 string to a PIL Image object."""
    image_bytes = base64.b64decode(image_base64)
    return Image.open(io.BytesIO(image_bytes))

def encode_image(image_path: str) -> str:
    """Encodes a PIL Image object to a base64 string."""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

def save_image(image: Image.Image, directory: str = "temp_images") -> str:
    """Saves a PIL Image object to a temporary file and returns its path."""
    temp_dir = os.path.join(os.path.dirname(__file__), directory)
    os.makedirs(temp_dir, exist_ok=True)
    filepath = os.path.join(temp_dir, f"{uuid.uuid4().hex}.png")
    image.save(filepath)
    return filepath