"""File utility functions for image handling."""
import base64
import tempfile
import uuid
from pathlib import Path
def generate_temp_path() -> str:
"""Generate a temporary file path for an image.
Returns:
Path to a temporary file with .png extension.
"""
temp_dir = Path(tempfile.gettempdir()) / "imagen_mcp"
temp_dir.mkdir(parents=True, exist_ok=True)
return str(temp_dir / f"image_{uuid.uuid4().hex[:8]}.png")
def generate_temp_dir() -> str:
"""Generate a temporary directory for batch images.
Returns:
Path to a temporary directory.
"""
temp_dir = (
Path(tempfile.gettempdir()) / "imagen_mcp" / f"batch_{uuid.uuid4().hex[:8]}"
)
temp_dir.mkdir(parents=True, exist_ok=True)
return str(temp_dir)
def save_image_to_file(b64_data: str, output_path: str) -> tuple[str, int]:
"""Save base64-encoded image data to a file.
Args:
b64_data: Base64-encoded image data.
output_path: Path where the image will be saved.
Returns:
Tuple of (absolute_path, file_size_bytes).
"""
path = Path(output_path)
# Create parent directories if they don't exist
path.parent.mkdir(parents=True, exist_ok=True)
# Decode and save
image_bytes = base64.b64decode(b64_data)
path.write_bytes(image_bytes)
return str(path.absolute()), len(image_bytes)