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, noise=False): header = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) raw = bytearray() row = width * 3 + 1 for _ in range(height): raw += b'\x00' + (os.urandom(row - 1) if noise else bytes(row - 1)) data = zlib.compress(bytes(raw), 0 if noise else 6) return header + chunk(b'IDAT', data) + chunk(b'IEND', b'') def png_header_only(width, height): header = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) return header + chunk(b'IDAT', zlib.compress(b'\x00')) + chunk(b'IEND', b'')