"""Image variants. The worker calls this; the API process does not resize.""" from __future__ import annotations import io import math from PIL import Image, ImageOps, UnidentifiedImageError from app import config from app.images import ImageRejected, inspect_image class PermanentJobError(Exception): def __init__(self, code: str) -> None: super().__init__(code) self.code = code class TransientJobError(Exception): def __init__(self, code: str = "processing_failed") -> None: super().__init__(code) self.code = code def _flatten(image: Image.Image) -> Image.Image: if image.mode == "RGB": return image rgba = image.convert("RGBA") background = Image.new("RGB", rgba.size, (255, 255, 255)) background.paste(rgba, mask=rgba.getchannel("A")) return background def _open_rgb(data: bytes, content_type: str) -> Image.Image: try: inspect_image(data, content_type) except ImageRejected as exc: raise PermanentJobError("invalid_image") from exc Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS try: with Image.open(io.BytesIO(data)) as image: image.load() oriented = ImageOps.exif_transpose(image) or image return _flatten(oriented).copy() except Image.DecompressionBombError as exc: raise PermanentJobError("invalid_image") from exc except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as exc: raise PermanentJobError("invalid_image") from exc def _fit_down(image: Image.Image, box: int) -> Image.Image: width, height = image.size scale = min(box / width, box / height, 1.0) target = (max(1, math.floor(width * scale)), max(1, math.floor(height * scale))) if target == (width, height): return image return image.resize(target, Image.Resampling.LANCZOS) def _crop_square(image: Image.Image, side: int) -> Image.Image: width, height = image.size edge = min(width, height) left = (width - edge) // 2 top = (height - edge) // 2 cropped = image.crop((left, top, left + edge, top + edge)) if cropped.size != (side, side): cropped = cropped.resize((side, side), Image.Resampling.LANCZOS) return cropped def _jpeg(image: Image.Image, quality: int) -> bytes: buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=quality, optimize=True) return buffer.getvalue() def _webp(image: Image.Image, quality: int) -> bytes: # method=6. EXIF is omitted because the saved image is a new RGB buffer. buffer = io.BytesIO() image.save(buffer, format="WEBP", quality=quality, method=6) return buffer.getvalue() def render(data: bytes, content_type: str, pipeline_version: int = 1) -> dict: """Return thumbnail, crop and optimized payloads. Does not touch storage. Version 1 is the contract profile (JPEG 90, WebP 80). A later version lowers quality so a stale writer cannot be confused with the newer bytes. """ jpeg_quality = 90 if pipeline_version <= 1 else 60 webp_quality = 80 if pipeline_version <= 1 else 50 image = _open_rgb(data, content_type) thumb = _fit_down(image, 256) crop = _crop_square(image, 128) optimized = _fit_down(image, 1280) return { "thumbnail": (_jpeg(thumb, jpeg_quality), "image/jpeg", thumb.size[0], thumb.size[1]), "crop": (_jpeg(crop, jpeg_quality), "image/jpeg", crop.size[0], crop.size[1]), "optimized": (_webp(optimized, webp_quality), "image/webp", optimized.size[0], optimized.size[1]), }