Files
2026-10-20 00:37:43 +03:00

55 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from PIL import Image
from app.config.settings import settings
from app.exceptions.invalid_image_exception import InvalidImageException
class ImageValidator:
MIN_WIDTH = 50
MIN_HEIGHT = 50
MAX_WIDTH = 10000
MAX_HEIGHT = 10000
# Полоски 50×10000 после уменьшения превращаются в 6×1280, а препроцессоры
# моделей растягивают короткую сторону до 224 — модели видят мусор.
MAX_ASPECT_RATIO = 20
def validate(
self,
image: Image.Image
) -> None:
# image.size берётся из заголовка — проверка не декодирует пиксели и
# годится для ещё не загруженной картинки
width, height = image.size
if width < self.MIN_WIDTH:
raise InvalidImageException(
f"Image width is too small: {width}"
)
if height < self.MIN_HEIGHT:
raise InvalidImageException(
f"Image height is too small: {height}"
)
if width > self.MAX_WIDTH:
raise InvalidImageException(
f"Image width is too large: {width}"
)
if height > self.MAX_HEIGHT:
raise InvalidImageException(
f"Image height is too large: {height}"
)
if width * height > settings.MAX_IMAGE_PIXELS:
raise InvalidImageException(
f"Image has too many pixels: {width}x{height}"
)
if max(width, height) > self.MAX_ASPECT_RATIO * min(width, height):
raise InvalidImageException(
f"Image aspect ratio is too extreme: {width}x{height}"
)