Xtool -mpng+reflate Link Today

def rebuild_png_with_mpng(input_path, output_path, streams, recompress_level=6, replace_map=None): """Rebuild PNG with modified MPNG streams""" with open(input_path, 'rb') as fin, open(output_path, 'wb') as fout: fout.write(fin.read(8)) # PNG signature

replace_map = None if replace_data: # Format: "idx:file.zlib" or "idx:file.raw" idx_str, path_str = replace_data.split(':') idx = int(idx_str) data = Path(path_str).read_bytes() # If raw, compress it if path_str.endswith('.raw'): data = zlib.compress(data, level) replace_map = {idx: data}

Here’s a solid, production-ready feature implementation for that adds support for MPNG (Multi-Piece PNG) + reflate (recompressing/zlib stream repair). xtool -mpng+reflate

def read_chunk(f): """Read PNG chunk: length, type, data, crc""" len_data = struct.unpack('>I', f.read(4))[0] chunk_type = f.read(4) data = f.read(len_data) crc = struct.unpack('>I', f.read(4))[0] return chunk_type, data, crc

if extract_only: for idx, comp in streams: raw = zlib.decompress(comp) out_file = f"{Path(input_png).stem}_stream_{idx}.raw" Path(out_file).write_bytes(raw) print(f"Extracted stream {idx} to {out_file}") return 'rb') as fin

if chunk_type == CHUNK_TYPE_IEND: break def mpng_reflate_cli(args): input_png = args.input output_png = args.output or input_png.replace('.png', '_reflated.png') level = args.recompress_level or 6 extract_only = args.extract_only replace_data = args.replace

def write_chunk(f, chunk_type, data): """Write PNG chunk with CRC""" f.write(struct.pack('>I', len(data))) f.write(chunk_type) f.write(data) crc = zlib.crc32(chunk_type + data) & 0xffffffff f.write(struct.pack('>I', crc)) crc""" len_data = struct.unpack('&gt

while True: chunk_type, data, crc = read_chunk(fin) if chunk_type == CHUNK_TYPE_MPNG: idx = struct.unpack('>I', data[:4])[0] if replace_map and idx in replace_map: new_compressed = replace_map[idx] else: # Find matching stream and reflate for stored_idx, comp in streams: if stored_idx == idx: new_compressed = reflate_stream(comp, recompress_level) break else: new_compressed = data[4:] # unchanged new_data = struct.pack('>I', idx) + new_compressed write_chunk(fout, CHUNK_TYPE_MPNG, new_data) else: # Copy other chunks unchanged fout.write(struct.pack('>I', len(data))) fout.write(chunk_type) fout.write(data) fout.write(struct.pack('>I', crc))