Files
mtusi2026lab4/student-tests/imagegen.py
T
2026-10-29 15:00:36 +03:00

35 lines
1.3 KiB
Python

"""Synthetic PNG builders for negative/limit tests (stdlib only, nothing stored in Git)."""
import os
import struct
import zlib
def chunk(kind, data):
body = kind + data
return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
def png(width, height, raw=None, level=6, color_type=2):
"""RGB (color_type=2) PNG; raw is the filtered scanline stream (default: random noise)."""
if raw is None:
row = 1 + 3 * width
raw = b''.join(b'\x00' + os.urandom(row - 1) for _ in range(height))
ihdr = struct.pack('>IIBBBBB', width, height, 8, color_type, 0, 0, 0)
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) +
chunk(b'IDAT', zlib.compress(raw, level)) + chunk(b'IEND', b''))
def near_limit_png(limit=10 * 1024 * 1024):
"""Valid noise PNG a little below the byte limit (stored deflate blocks)."""
width = 1000
height = (limit - 64 * 1024) // (1 + 3 * width)
data = png(width, height, level=0)
assert len(data) <= limit, len(data)
return data
def bomb_png(width=20000, height=20000):
"""Header declares 400M pixels, the compressed payload is tiny."""
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) +
chunk(b'IDAT', zlib.compress(b'\x00' * 4096, 9)) + chunk(b'IEND', b''))