"""Derivatives for pipeline v1. thumbnail: JPEG quality 85, fit inside 256×256, never upscaled, EXIF orientation applied, alpha composited on white. 320×200 becomes 256×160. crop: JPEG quality 85, centered square resized to 128×128. Sources smaller than 128 px are scaled up. Orientation and alpha match the thumbnail. optimized: WebP quality 80, encoder method 4, fit inside 1280×1280, never upscaled. EXIF is not written. A small source is not promised to get smaller. Bytes are capped at 10 MiB and pixels at 40 million before decode. The worker container memory limit is the hard cap around that. """ import io from typing import Dict, Tuple from PIL import Image, ImageOps, UnidentifiedImageError from .errors import ApiError from .images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES, inspect_image THUMBNAIL_BOX = 256 THUMBNAIL_JPEG_QUALITY = 85 CROP_SIDE = 128 CROP_JPEG_QUALITY = 85 OPTIMIZED_BOX = 1280 OPTIMIZED_WEBP_QUALITY = 80 OPTIMIZED_WEBP_METHOD = 4 class ImageRejected(Exception): """The bytes are not a PNG/JPEG we can decode inside the pixel limit.""" def _fit(width: int, height: int, box: int) -> Tuple[int, int]: """Fit inside box×box, keep the aspect ratio, never upscale, round down, at least 1 px.""" if width <= box and height <= box: return width, height fitted_width = box fitted_height = (height * box) // width if fitted_height > box: fitted_height = box fitted_width = (width * box) // height return max(1, fitted_width), max(1, fitted_height) def _on_white(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 _encode(image: Image.Image, fmt: str, **options) -> bytes: """Save a metadata-free copy. The caller's image is left open.""" bare = Image.frombytes(image.mode, image.size, image.tobytes()) try: buffer = io.BytesIO() bare.save(buffer, format=fmt, **options) return buffer.getvalue() finally: bare.close() def _fitted(base: Image.Image, box: int) -> Tuple[Image.Image, int, int]: width, height = _fit(base.width, base.height, box) if (width, height) == base.size: return base, width, height return base.resize((width, height), Image.Resampling.LANCZOS), width, height def _jpeg_box(base: Image.Image, box: int, quality: int) -> Dict[str, object]: image, width, height = _fitted(base, box) try: blob = _encode(image, 'JPEG', quality=quality) finally: if image is not base: image.close() return {'content_type': 'image/jpeg', 'width': width, 'height': height, 'data': blob} def _crop(base: Image.Image) -> Dict[str, object]: side = min(base.width, base.height) left = (base.width - side) // 2 top = (base.height - side) // 2 square = base if side == base.width and side == base.height else base.crop((left, top, left + side, top + side)) try: sized = square if square.size == (CROP_SIDE, CROP_SIDE) else square.resize( (CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS ) try: blob = _encode(sized, 'JPEG', quality=CROP_JPEG_QUALITY) finally: if sized is not square: sized.close() finally: if square is not base: square.close() return {'content_type': 'image/jpeg', 'width': CROP_SIDE, 'height': CROP_SIDE, 'data': blob} def _webp(base: Image.Image) -> Dict[str, object]: image, width, height = _fitted(base, OPTIMIZED_BOX) try: blob = _encode(image, 'WEBP', quality=OPTIMIZED_WEBP_QUALITY, method=OPTIMIZED_WEBP_METHOD) finally: if image is not base: image.close() return {'content_type': 'image/webp', 'width': width, 'height': height, 'data': blob} def render_variants(data: bytes) -> Dict[str, Dict[str, object]]: """Decode once and return thumbnail, crop and optimized. Raises ImageRejected.""" if len(data) > MAX_UPLOAD_BYTES: raise ImageRejected() try: inspect_image(data) except ApiError: raise ImageRejected() from None Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS source = Image.open(io.BytesIO(data)) owned = [source] try: oriented = ImageOps.exif_transpose(source) if oriented is not source: owned.append(oriented) source = oriented source.load() width, height = source.size if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS: raise ImageRejected() base = _on_white(source) if base is not source: owned.append(base) return { 'thumbnail': _jpeg_box(base, THUMBNAIL_BOX, THUMBNAIL_JPEG_QUALITY), 'crop': _crop(base), 'optimized': _webp(base), } except ImageRejected: raise except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError, MemoryError): raise ImageRejected() from None finally: for image in owned: image.close() def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]: """JPEG thumbnail bytes and the size actually written. 320×200 becomes 256×160.""" item = render_variants(data)['thumbnail'] return item['data'], int(item['width']), int(item['height'])