PyPNG
PyPNG is a pure Python library designed for reading, writing, and manipulating PNG (Portable Network Graphics) images. It provides a simple, Pythonic interface and boasts no external dependencies. The current stable version is `0.20220715.0`, with updates released as needed.
Warnings
- breaking The `lenient` flag has been removed. PNG chunk checksum errors are now treated as warnings instead of exceptions and can be managed using Python's standard `warnings` module.
- breaking The `interlace` keyword argument has been removed from the `Writer` class, and interlaced output is no longer supported.
- breaking Passing an empty file to PyPNG now raises a built-in `EOFError` instead of `png.FormatError`. This change helps distinguish empty file issues from genuine format errors.
- gotcha Files for reading or writing PNGs must always be opened in binary mode (e.g., `'wb'` for writing, `'rb'` for reading) to prevent data corruption or unexpected errors.
- gotcha Incorrect bit depth specification or pixel data formatting can lead to corrupted images. Pixel data must match the `Writer` configuration (e.g., grayscale, RGB, RGBA) and the declared bit depth.
- gotcha When calculating image dimensions, especially for `width` from row data (e.g., `len(row) / channels_per_pixel`), ensure you use integer division (`//`) instead of float division (`/`). Using float division where an integer is expected can lead to `TypeError`.
Install
-
pip install pypng
Imports
- png
import png
Quickstart
import png
import os
# Create a simple 2x2 grayscale image (Luminance) with a bit depth of 8
rows = [
[255, 0], # White, Black
[0, 255] # Black, White
]
# Create an image from a 2D array and save it
image_file_path = 'simple_image.png'
png.from_array(rows, 'L').save(image_file_path)
print(f"Image saved to {image_file_path}")
# Clean up the created file
# os.remove(image_file_path)