Files
mtusi2026lab5/src/images.py
T

75 lines
2.7 KiB
Python

"""Размеры PNG/JPEG по заголовкам, без распаковки пикселей."""
from __future__ import annotations
from errors import ApiError
PNG_SIG = b"\x89PNG\r\n\x1a\n"
# SOF0..SOF3, SOF5..SOF7, SOF9..SOF11, SOF13..SOF15. Не DHT/JPG/DAC.
_JPEG_SOF = {
0xC0, 0xC1, 0xC2, 0xC3,
0xC5, 0xC6, 0xC7,
0xC9, 0xCA, 0xCB,
0xCD, 0xCE, 0xCF,
}
def sniff(data: bytes) -> str:
if data.startswith(PNG_SIG):
return "image/png"
if data.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
raise ApiError(415, "unsupported_media_type", "Файл не PNG и не JPEG")
def dimensions(data: bytes, content_type: str) -> tuple[int, int]:
if content_type == "image/png":
return _png_size(data)
if content_type == "image/jpeg":
return _jpeg_size(data)
raise ApiError(415, "unsupported_media_type", "Файл не PNG и не JPEG")
def _png_size(data: bytes) -> tuple[int, int]:
if len(data) < 24 or not data.startswith(PNG_SIG) or data[12:16] != b"IHDR":
raise ApiError(415, "unsupported_media_type", "Повреждённый PNG")
width = int.from_bytes(data[16:20], "big")
height = int.from_bytes(data[20:24], "big")
if width < 1 or height < 1:
raise ApiError(415, "unsupported_media_type", "Повреждённый PNG")
return width, height
def _jpeg_size(data: bytes) -> tuple[int, int]:
if len(data) < 4 or data[:2] != b"\xff\xd8":
raise ApiError(415, "unsupported_media_type", "Повреждённый JPEG")
index = 2
size = len(data)
while index < size:
if data[index] != 0xFF:
break
while index < size and data[index] == 0xFF:
index += 1
if index >= size:
break
marker = data[index]
index += 1
if marker in (0xD8, 0xD9) or marker == 0xDA:
break
if marker == 0x01 or 0xD0 <= marker <= 0xD7:
continue
if index + 2 > size:
break
segment = int.from_bytes(data[index:index + 2], "big")
if segment < 2 or index + segment > size:
raise ApiError(415, "unsupported_media_type", "Повреждённый JPEG")
if marker in _JPEG_SOF:
if segment < 7:
raise ApiError(415, "unsupported_media_type", "Повреждённый JPEG")
height = int.from_bytes(data[index + 3:index + 5], "big")
width = int.from_bytes(data[index + 5:index + 7], "big")
if width < 1 or height < 1:
raise ApiError(415, "unsupported_media_type", "Повреждённый JPEG")
return width, height
index += segment
raise ApiError(415, "unsupported_media_type", "В JPEG нет размеров")