"""Read an image's pixel dimensions from its header, with no image library. A level's `mapwidth`/`mapheight` are the coordinate space every marker on it is expressed in, so getting them wrong moves every marker relative to the drawing. Reading them off the uploaded file removes the most likely way to get them wrong, which is somebody typing what they remember. Pillow would do this in one line and is not a dependency. Adding it would mean a new cp314 win_amd64 wheel in the offline installer's hash-pinned wheelhouse - built on Windows, verified against bundle-lock.json, shipped in a 240 MB installer - to read two integers out of a header. This is the cheaper trade. Returns (width, height), or (None, None) when the format is not one of these or the header is truncated. A caller must treat None as "ask the operator" and never as a default. """ import re import struct def png_size(data): # An IHDR chunk always follows the 8-byte signature, and its first two # fields are width and height as big-endian 32-bit integers. if len(data) < 24 or data[:8] != b'\x89PNG\r\n\x1a\n': return None, None if data[12:16] != b'IHDR': return None, None width, height = struct.unpack('>II', data[16:24]) return width, height def gif_size(data): if len(data) < 10 or data[:6] not in (b'GIF87a', b'GIF89a'): return None, None width, height = struct.unpack('> 14) & 0x3FFF) + 1 if kind == b'VP8X': width = int.from_bytes(data[24:27], 'little') + 1 height = int.from_bytes(data[27:30], 'little') + 1 return width, height return None, None def jpeg_size(data): """Walk the marker segments to the start-of-frame, which carries the size. JPEG has no fixed header offset - the dimensions live in whichever SOF marker the encoder used, after any number of application and comment segments of varying length. So this walks rather than indexes. """ if len(data) < 4 or data[:2] != b'\xff\xd8': return None, None index = 2 end = len(data) while index < end - 9: if data[index] != 0xFF: index += 1 continue marker = data[index + 1] # SOF0 through SOF15, excluding the DHT/JPG/DAC markers interleaved # in that range, all carry height then width at the same offset. if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF): height, width = struct.unpack('>HH', data[index + 5:index + 9]) return width, height if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD9: index += 2 continue segment = struct.unpack('>H', data[index + 2:index + 4])[0] index += 2 + segment return None, None def svg_size(data): """SVG states a size in attributes, or implies one through viewBox. Width and height may carry units (mm, in, pt) or be percentages, and a percentage says nothing about pixels - so a unit that is not px falls back to the viewBox, which is unitless user space and is what a renderer scales to. """ try: head = data[:4096].decode('utf-8', errors='replace') except Exception: return None, None if '