forked from mtusi2026/mtusi2026lab4
51 lines
1.7 KiB
Python
51 lines
1.7 KiB
Python
"""Synthetic PNG helpers (stdlib only); same semantics as app/test/support/png.ts."""
|
|
import random
|
|
import struct
|
|
import zlib
|
|
|
|
SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
NOISE_WIDTH = 1024
|
|
NOISE_ROW = 1 + NOISE_WIDTH * 3
|
|
|
|
|
|
def chunk(kind: bytes, data: bytes) -> bytes:
|
|
crc = zlib.crc32(kind + data) & 0xFFFFFFFF
|
|
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", crc)
|
|
|
|
|
|
def build_png(width: int, height: int, idat: bytes) -> bytes:
|
|
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
|
return SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")
|
|
|
|
|
|
def pad_png(data: bytes, size: int) -> bytes:
|
|
"""Insert a private ancillary chunk before IEND to reach exactly `size` bytes."""
|
|
extra = size - len(data)
|
|
if extra == 0:
|
|
return data
|
|
if extra < 12:
|
|
raise ValueError("padding needs at least 12 bytes")
|
|
return data[:-12] + chunk(b"prVt", bytes(extra - 12)) + data[-12:]
|
|
|
|
|
|
def _noise_of_height(height: int, rng: random.Random) -> bytes:
|
|
raw = bytearray(rng.randbytes(NOISE_ROW * height))
|
|
for row in range(height):
|
|
raw[row * NOISE_ROW] = 0 # filter type "none"
|
|
compressor = zlib.compressobj(0)
|
|
return build_png(NOISE_WIDTH, height, compressor.compress(bytes(raw)) + compressor.flush())
|
|
|
|
|
|
def noise_png(size: int, seed: int = 0) -> bytes:
|
|
"""Incompressible, structurally valid PNG of exactly `size` bytes."""
|
|
rng = random.Random(seed)
|
|
height = max(1, size // NOISE_ROW)
|
|
while True:
|
|
png = _noise_of_height(height, rng)
|
|
if len(png) > size or 0 < size - len(png) < 12:
|
|
height -= 1
|
|
if height < 1:
|
|
raise ValueError("size is too small")
|
|
continue
|
|
return pad_png(png, size)
|