The png module encodes and decodes PNG and BMP images using only the Python standard library (zlib, struct). It provides a shared Image dataclass for format conversion and a matrix_to_png / png_to_matrix API that exploits PNG row filters for efficient 2D numeric data compression.
frompngimportencode_png,Image# Create a 2x2 red imagepixels=bytes([255,0,0,255,0,0,0,255,0,0,255,0])img=Image(width=2,height=2,data=pixels,mode="RGB")# Save to fileencode_png(img,"output.png")# Or get bytespng_bytes=encode_png(img)
importmathfrompngimportmatrix_to_png,png_to_matrix# Compress a 2D float matrix as PNGmatrix=[[math.sin(x*0.1+y*0.2)forxinrange(256)]foryinrange(256)]matrix_to_png(matrix,"data.png",bit_depth=16)# Reconstruct (lossless for integers, quantized for floats)restored=png_to_matrix("data.png")
frompngimportencode_png,Imageimg=Image(width=100,height=100,data=pixels,mode="RGB")# Auto-select best filter per row (default)encode_png(img,filter_strategy="auto")# Force a specific filterencode_png(img,filter_strategy="sub")# good for photosencode_png(img,filter_strategy="paeth")# good for gradientsencode_png(img,filter_strategy="none")# fastest, largest