forked from mtusi2026/mtusi2026lab4
37 lines
1.1 KiB
Python
37 lines
1.1 KiB
Python
"""Small deterministic PNG builders for standard-library-only acceptance tests."""
|
|
import random
|
|
import struct
|
|
import zlib
|
|
|
|
|
|
def _chunk(name, data):
|
|
kind = name.encode("ascii")
|
|
return (
|
|
struct.pack(">I", len(data))
|
|
+ kind
|
|
+ data
|
|
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
|
)
|
|
|
|
|
|
def solid_gray_png(width, height):
|
|
row_size = (width + 7) // 8
|
|
raw = (b"\x00" + bytes(row_size)) * height
|
|
image_header = struct.pack(">IIBBBBB", width, height, 1, 0, 0, 0, 0)
|
|
return b"\x89PNG\r\n\x1a\n" + _chunk("IHDR", image_header) + _chunk(
|
|
"IDAT", zlib.compress(raw)
|
|
) + _chunk("IEND", b"")
|
|
|
|
|
|
def noisy_rgb_png(width, height, seed=42024):
|
|
image_header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
|
compressor = zlib.compressobj(level=1)
|
|
compressed = bytearray()
|
|
rng = random.Random(seed)
|
|
for _ in range(height):
|
|
compressed.extend(compressor.compress(b"\x00" + rng.randbytes(width * 3)))
|
|
compressed.extend(compressor.flush())
|
|
return b"\x89PNG\r\n\x1a\n" + _chunk("IHDR", image_header) + _chunk(
|
|
"IDAT", bytes(compressed)
|
|
) + _chunk("IEND", b"")
|