from io import BytesIO from typing import Tuple, Optional from PIL import Image import logging logger = logging.getLogger(__name__) def create_thumbnail(image_data: bytes, size: Tuple[int, int] = (800, 800)) -> Optional[bytes]: """ Creates a thumbnail from image bytes. Returns the thumbnail as bytes (JPEG format) or None if failed. """ try: with Image.open(BytesIO(image_data)) as img: # Convert to RGB if necessary (e.g. for RGBA/P images saving as JPEG) if img.mode in ('RGBA', 'P'): img = img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, format='JPEG', quality=85) thumb_io.seek(0) return thumb_io.read() except Exception as e: logger.error(f"Failed to create thumbnail: {e}") return None