24 lines
1.1 KiB
Python
24 lines
1.1 KiB
Python
"""Синхронная проверка изображения; вызывается только из ограниченного процесса."""
|
|
|
|
from pathlib import Path
|
|
import warnings
|
|
|
|
from PIL import Image
|
|
|
|
from app.errors.exceptions import payload_too_large, unsupported_media_type
|
|
|
|
|
|
def decode_image(path: Path, content_type: str, max_pixels: int) -> None:
|
|
Image.MAX_IMAGE_PIXELS = max_pixels
|
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
|
with Image.open(path, formats=["PNG", "JPEG"]) as image:
|
|
if image.width * image.height > max_pixels:
|
|
raise payload_too_large("Превышен лимит пикселей изображения")
|
|
image_format = image.format
|
|
if image_format is None or Image.MIME.get(image_format) != content_type:
|
|
raise unsupported_media_type("Содержимое не соответствует Content-Type")
|
|
image.verify()
|
|
# Для JPEG одной verify() недостаточно: декодировать весь оригинал.
|
|
with Image.open(path, formats=["PNG", "JPEG"]) as image:
|
|
image.load()
|