Files
mtusi2026lab4/app/images.py
T

39 lines
1.3 KiB
Python

"""Image checks without network access."""
import warnings
from PIL import Image, UnidentifiedImageError
MAX_BYTES = 10_485_760
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
class InvalidImage(ValueError):
pass
class TooManyPixels(ValueError):
pass
def validate_image(file, mime):
try:
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombWarning)
file.seek(0)
with Image.open(file) as img:
if img.width * img.height > MAX_PIXELS:
raise TooManyPixels()
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(img.format)
if actual != mime or actual is None:
raise InvalidImage()
if getattr(img, 'n_frames', 1) != 1:
raise InvalidImage()
img.verify()
file.seek(0)
with Image.open(file) as img:
img.load() # Detect truncated JPEG/pixel data, not only its header.
except (Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
raise TooManyPixels() from exc
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
if isinstance(exc, TooManyPixels):
raise
raise InvalidImage() from exc
finally:
file.seek(0)