import struct import zlib from io import BytesIO from pathlib import Path from PIL import Image SAMPLE = (Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png").read_bytes() SIGNATURE = b"\x89PNG\r\n\x1a\n" def chunk(kind: bytes, data: bytes) -> bytes: crc = zlib.crc32(kind + data) return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", crc) def png(width: int, height: int, *, size: int | None = None, rows: bool = True) -> bytes: header = struct.pack(">IIBBBBB", width, height, 1, 0, 0, 0, 0) raw = (b"\x00" * (1 + (width + 7) // 8)) * height if rows else b"\x00" head = SIGNATURE + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw, 9)) tail = chunk(b"IEND", b"") if size is not None: head += chunk(b"prVt", b"\x00" * (size - len(head) - len(tail) - 12)) return head + tail def encoded(kind: str, width: int = 640, height: int = 480) -> bytes: buffer = BytesIO() Image.effect_noise((width, height), 64).convert("RGB").save(buffer, kind) return buffer.getvalue() JPEG = encoded("JPEG") GIF = encoded("GIF") WEBP = encoded("WEBP")