# SPDX-License-Identifier: MIT """A small PNG reader and writer for the picture tests (no Pillow under PyPy). Written from the PNG specification (W3C, "Portable Network Graphics (PNG) Specification", chunk layout, filter types 0-4 and the Paeth predictor). Reads 8-bit greyscale, RGB, RGBA, grey+alpha and palette images (bit depths 1-8 for palette and grey), non-interlaced; writes 8-bit RGB. Also reads a 24-bit BMP (Microsoft's BITMAPINFOHEADER layout), which one of krom's ".png" files is. """ from __future__ import annotations import struct import zlib from pathlib import Path def write_png(path: str | Path, width: int, height: int, rgb: bytes | bytearray) -> None: """Write ``rgb`` (``width * height * 3`` bytes, rows top to bottom) as a PNG.""" stride = width * 3 raw = bytearray() for y in range(height): raw.append(0) raw += rgb[y * stride : (y + 1) * stride] def chunk(kind: bytes, data: bytes) -> bytes: return ( struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) ) header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) Path(path).write_bytes( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b"") ) def _paeth(a: int, b: int, c: int) -> int: p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: return a if pb <= pc: return b return c def _read_bmp(data: bytes, path: str | Path) -> tuple[int, int, bytearray]: """An uncompressed 24-bit Windows BMP (BITMAPINFOHEADER), as RGB.""" offset = struct.unpack(" tuple[int, int, bytearray]: """Read a PNG as (width, height, RGB bytes); alpha is dropped.""" data = Path(path).read_bytes() if data[:2] == b"BM": # krom's Perspective.png is a Windows BMP under a .png name. return _read_bmp(data, path) if data[:8] != b"\x89PNG\r\n\x1a\n": raise ValueError(f"{path}: not a PNG") pos = 8 idat = bytearray() palette = b"" width = height = depth = colour = interlace = 0 while pos < len(data): (length,) = struct.unpack(">I", data[pos : pos + 4]) kind = data[pos + 4 : pos + 8] body = data[pos + 8 : pos + 8 + length] pos += 12 + length if kind == b"IHDR": width, height, depth, colour, _, _, interlace = struct.unpack(">IIBBBBB", body) elif kind == b"PLTE": palette = body elif kind == b"IDAT": idat += body elif kind == b"IEND": break if interlace: raise ValueError(f"{path}: interlaced PNGs are not supported") channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[colour] if depth == 16: raise ValueError(f"{path}: 16-bit PNGs are not supported") bits = channels * depth stride = (width * bits + 7) // 8 bpp = max(1, bits // 8) raw = zlib.decompress(bytes(idat)) out = bytearray(width * height * 3) prev = bytearray(stride) o = 0 for y in range(height): base = y * (stride + 1) kind = raw[base] line = bytearray(raw[base + 1 : base + 1 + stride]) if kind == 1: for i in range(bpp, stride): line[i] = (line[i] + line[i - bpp]) & 0xFF elif kind == 2: for i in range(stride): line[i] = (line[i] + prev[i]) & 0xFF elif kind == 3: for i in range(stride): left = line[i - bpp] if i >= bpp else 0 line[i] = (line[i] + ((left + prev[i]) >> 1)) & 0xFF elif kind == 4: for i in range(stride): left = line[i - bpp] if i >= bpp else 0 upleft = prev[i - bpp] if i >= bpp else 0 line[i] = (line[i] + _paeth(left, prev[i], upleft)) & 0xFF prev = line if depth == 8: for x in range(width): p = x * channels if colour == 2 or colour == 6: out[o] = line[p] out[o + 1] = line[p + 1] out[o + 2] = line[p + 2] elif colour == 3: i = line[p] * 3 out[o : o + 3] = palette[i : i + 3] else: out[o] = out[o + 1] = out[o + 2] = line[p] o += 3 else: mask = (1 << depth) - 1 for x in range(width): bit = x * depth value = (line[bit >> 3] >> (8 - depth - (bit & 7))) & mask if colour == 3: i = value * 3 out[o : o + 3] = palette[i : i + 3] else: grey = value * 255 // mask out[o] = out[o + 1] = out[o + 2] = grey o += 3 return width, height, out __all__ = ["read_png", "write_png"]