import io from PIL import Image, ImageOps, UnidentifiedImageError from app.codec import fitted_size from app.errors import AppError, too_large, unsupported from app.settings import settings Image.MAX_IMAGE_PIXELS = settings.max_pixels def _open(data): try: with Image.open(io.BytesIO(data)) as image: image.verify() with Image.open(io.BytesIO(data)) as image: width, height = image.size if width < 1 or height < 1 or width * height > settings.max_pixels: raise too_large() image.load() return image.copy() except AppError: raise except Image.DecompressionBombError as exc: raise too_large() from exc except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombWarning) as exc: raise unsupported() from exc def validate_image(data): _open(data).close() def _rgb(image): if image.mode == "RGB": return image if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info): rgba = image.convert("RGBA") background = Image.new("RGB", rgba.size, (255, 255, 255)) background.paste(rgba, mask=rgba.getchannel("A")) return background return image.convert("RGB") def thumbnail_jpeg(data): image = _open(data) try: image = ImageOps.exif_transpose(image) image = _rgb(image) target = fitted_size(image.width, image.height, 256) if (image.width, image.height) != target: image = image.resize(target, Image.Resampling.LANCZOS) buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=85, optimize=True) blob = buffer.getvalue() return blob, image.width, image.height except AppError: raise except (UnidentifiedImageError, OSError, ValueError) as exc: raise unsupported() from exc finally: image.close()