from io import BytesIO from PIL import Image, UnidentifiedImageError from fastapi import HTTPException MAX_BYTES = 10 * 1024 * 1024 MAX_PIXELS = 40_000_000 ALLOWED = {"PNG": "image/png", "JPEG": "image/jpeg"} def validate_image_file(fileobj, declared_type: str): """Validate a seekable, size-limited file without loading its full encoded bytes.""" try: fileobj.seek(0) with Image.open(fileobj) as image: fmt = image.format width, height = image.size if fmt not in ALLOWED: raise HTTPException(415, "Only PNG and JPEG are supported") if width * height > MAX_PIXELS: raise HTTPException(413, "Image exceeds 40 million pixels") image.verify() fileobj.seek(0) with Image.open(fileobj) as image: image.load() except HTTPException: raise except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError): raise HTTPException(415, "Invalid or corrupted image") from None actual_type = ALLOWED[fmt] if declared_type != actual_type: raise HTTPException(415, "Content-Type does not match image content") fileobj.seek(0) return actual_type, width, height def validate_image(data: bytes, declared_type: str): if not data: raise HTTPException(415, "Empty image") if len(data) > MAX_BYTES: raise HTTPException(413, "Image exceeds 10 MiB") return validate_image_file(BytesIO(data), declared_type)