"""Cheap header-only PNG/JPEG probing: magic, declared MIME and pixel limit.""" import struct PNG_MAGIC = b"\x89PNG\r\n\x1a\n" JPEG_MAGIC = b"\xff\xd8\xff" SOF_MARKERS = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} class InvalidImage(ValueError): pass def probe(data): """Return (content_type, width, height) without decoding the whole image.""" if data.startswith(PNG_MAGIC): if len(data) < 24 or data[12:16] != b"IHDR": raise InvalidImage("truncated PNG") width, height = struct.unpack(">II", data[16:24]) if width == 0 or height == 0: raise InvalidImage("invalid PNG dimensions") return "image/png", width, height if data[:3] == JPEG_MAGIC: i = 2 while i + 9 < len(data): if data[i] != 0xFF: i += 1 continue marker = data[i + 1] if marker == 0xFF: i += 1 continue if marker == 0xD8 or 0xD0 <= marker <= 0xD7 or marker == 0x01: i += 2 continue if marker == 0xD9: break length = struct.unpack(">H", data[i + 2:i + 4])[0] if length < 2 or i + 2 + length > len(data): raise InvalidImage("truncated JPEG segment") if marker in SOF_MARKERS: height, width = struct.unpack(">HH", data[i + 5:i + 9]) if width == 0 or height == 0: raise InvalidImage("invalid JPEG dimensions") return "image/jpeg", width, height i += 2 + length raise InvalidImage("JPEG has no SOF marker") raise InvalidImage("not a PNG or JPEG")