forked from mtusi2026/mtusi2026lab4
36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
import hashlib
|
|
import struct
|
|
import zlib
|
|
|
|
|
|
def chunk(kind, payload):
|
|
return (
|
|
struct.pack(">I", len(payload))
|
|
+ kind
|
|
+ payload
|
|
+ struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)
|
|
)
|
|
|
|
|
|
def make_png(width, height, size, seed):
|
|
compressor = zlib.compressobj(6)
|
|
compressed = []
|
|
for y in range(height):
|
|
color = bytes(((seed + y) % 256, (seed + y * 3) % 256, (seed + y * 7) % 256))
|
|
compressed.append(compressor.compress(b"\0" + color * width))
|
|
compressed.append(compressor.flush())
|
|
header = b"\x89PNG\r\n\x1a\n" + chunk(
|
|
b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
|
)
|
|
image = header + chunk(b"IDAT", b"".join(compressed))
|
|
# npAD: ancillary, private, reserved uppercase, unsafe-to-copy. The same
|
|
# decoded pixels occur at both encoded sizes; only this chunk grows.
|
|
remaining = size - len(image) - len(chunk(b"IEND", b"")) - 12
|
|
if remaining < 0:
|
|
raise ValueError("target size cannot hold this PNG")
|
|
block = hashlib.sha256(str(seed).encode("ascii")).digest()
|
|
padding = (block * ((remaining + len(block) - 1) // len(block)))[:remaining]
|
|
result = image + chunk(b"npAD", padding) + chunk(b"IEND", b"")
|
|
assert len(result) == size
|
|
return result
|