QuizFrog/backend/app/utils/image_utils.py

25 lines
710 B
Python

from __future__ import annotations
import io
from PIL import Image
MAX_WIDTH = 1920
MAX_HEIGHT = 1920
JPEG_QUALITY = 85
async def preprocess_image(image_bytes: bytes, filename: str) -> tuple[bytes, str]:
"""Compress and normalize uploaded images."""
img = Image.open(io.BytesIO(image_bytes))
# Convert to RGB (remove alpha channel)
if img.mode in ("RGBA", "P", "LA"):
img = img.convert("RGB")
# Resize proportionally if too large
if img.width > MAX_WIDTH or img.height > MAX_HEIGHT:
img.thumbnail((MAX_WIDTH, MAX_HEIGHT), Image.LANCZOS)
output = io.BytesIO()
img.save(output, format="JPEG", quality=JPEG_QUALITY)
return output.getvalue(), "image/jpeg"