from __future__ import annotations import io from typing import Tuple from PIL import Image, ImageOps, UnidentifiedImageError from .images import max_image_pixels def make_thumbnail_jpeg(data: bytes) -> Tuple[bytes, int, int]: Image.MAX_IMAGE_PIXELS = max_image_pixels() try: with Image.open(io.BytesIO(data)) as img: img = ImageOps.exif_transpose(img) if img.mode in {"RGBA", "LA"} or (img.mode == "P" and "transparency" in img.info): rgba = img.convert("RGBA") background = Image.new("RGB", rgba.size, (255, 255, 255)) background.paste(rgba, mask=rgba.split()[-1]) img = background else: img = img.convert("RGB") width, height = img.size if width < 1 or height < 1: raise ValueError("invalid image size") if width > 256 or height > 256: scale = min(256 / width, 256 / height) new_w = max(1, int(width * scale)) new_h = max(1, int(height * scale)) img = img.resize((new_w, new_h), Image.Resampling.LANCZOS) else: new_w, new_h = width, height out = io.BytesIO() img.save(out, format="JPEG", quality=85, optimize=True) return out.getvalue(), new_w, new_h except Image.DecompressionBombError as exc: raise ValueError("image exceeds pixel limit") from exc except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as exc: raise ValueError("invalid image") from exc