Files
mtusi2026lab6-Leskovskiy/src/images.py
T

26 lines
996 B
Python

import io
from PIL import Image, UnidentifiedImageError
from . import config
from .errors import ApiError
def validate_image(data: bytes) -> tuple[str, int, int, int]:
"""Возвращает (content_type, width, height, size)."""
if not data:
raise ApiError(400, "invalid_request", "empty body")
if len(data) > config.MAX_UPLOAD_BYTES:
raise ApiError(413, "payload_too_large", "file too large")
head = data[:8]
if head.startswith(b"\x89PNG\r\n\x1a\n"):
ctype = "image/png"
elif head.startswith(b"\xff\xd8\xff"):
ctype = "image/jpeg"
else:
raise ApiError(415, "unsupported_media_type", "only PNG/JPEG")
try:
img = Image.open(io.BytesIO(data))
w, h = img.size
except UnidentifiedImageError:
raise ApiError(415, "unsupported_media_type", "invalid image")
if w * h > config.MAX_IMAGE_PIXELS:
raise ApiError(413, "payload_too_large", "too many pixels")
return ctype, w, h, len(data)