forked from mtusi2026/mtusi2026lab4
24 lines
795 B
Python
24 lines
795 B
Python
import io
|
|
from PIL import Image
|
|
|
|
def detect_image_type(data: bytes) -> str | None:
|
|
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
return "image/png"
|
|
if data.startswith(b"\xff\xd8\xff"):
|
|
return "image/jpeg"
|
|
return None
|
|
|
|
def check_image(data: bytes, allowed_types: list[str]) -> tuple[str, int, int]:
|
|
content_type = detect_image_type(data)
|
|
if not content_type or content_type not in allowed_types:
|
|
raise ValueError("Invalid or unsupported image type")
|
|
|
|
try:
|
|
with Image.open(io.BytesIO(data)) as img:
|
|
width, height = img.size
|
|
if width * height > 40_000_000:
|
|
raise ValueError("Too many pixels")
|
|
except Exception as e:
|
|
raise ValueError(f"Broken image: {e}")
|
|
|
|
return content_type, width, height |