### Install pyoxipng Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/README.md Install the pyoxipng library using pip. Requires Python 3.8+. ```bash pip install pyoxipng ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Install all necessary development dependencies using Pipenv. ```sh pipenv install --dev ``` -------------------------------- ### Oxipng Optimize with Multiple Filters Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Example of using oxipng.optimize to try multiple RowFilters and select the best one for optimization. Ensure the oxipng library is imported. ```python import oxipng # Try multiple filters and use the best oxipng.optimize( "/path/to/image.png", filter=[ oxipng.RowFilter.NoOp, oxipng.RowFilter.Sub, oxipng.RowFilter.Up, oxipng.RowFilter.Paeth, oxipng.RowFilter.Brute ] ) ``` -------------------------------- ### Optimize PNG file on disk (overwrite) Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Optimize a PNG file located on disk. This example overwrites the original file with the optimized version. ```python oxipng.optimize("/path/to/image.png") ``` -------------------------------- ### In-Memory PNG Optimization with Pyoxipng Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Demonstrates optimizing raw pixel data in memory to create an optimized PNG without writing intermediate files. This example uses NumPy for pixel data and custom filters with Zopfli compression. ```python import oxipng import numpy as np # Create raw image data width, height = 512, 512 pixel_data = np.random.randint(0, 256, (height, width, 4), dtype=np.uint8).tobytes() # Optimize with multiple filter types and zopfli compression raw = oxipng.RawImage(pixel_data, width, height) optimized = raw.create_optimized_png( level=6, filter=[ oxipng.RowFilter.Paeth, oxipng.RowFilter.Entropy, oxipng.RowFilter.Brute ], deflate=oxipng.Deflaters.zopfli(100) ) with open("/path/to/output.png", "wb") as f: f.write(optimized) ``` -------------------------------- ### PNG Optimization with Fallback Strategy Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/errors.md Implement a fallback mechanism to retry optimization with different settings if the initial attempt fails. This example first tries aggressive settings and then retries with error fixing enabled. ```python import oxipng def optimize_with_fallback(input_path, output_path): try: # Try optimizing with aggressive settings oxipng.optimize( input_path, output_path, level=6, deflate=oxipng.Deflaters.zopfli(255) ) print(f"Optimized: {input_path}") except oxipng.PngError as e: print(f"Aggressive optimization failed, retrying with fix_errors: {e}") try: # Retry with error fixing enabled oxipng.optimize( input_path, output_path, level=2, fix_errors=True ) print(f"Optimized with error fixing: {input_path}") except oxipng.PngError as e2: print(f"Cannot optimize {input_path}: {e2}") return False return True ``` -------------------------------- ### Oxipng Optimize with Single Filter Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Example of using oxipng.optimize with a single specified RowFilter. Ensure the oxipng library is imported. ```python import oxipng # Use a single filter oxipng.optimize("/path/to/image.png", filter=[oxipng.RowFilter.NoOp]) ``` -------------------------------- ### Configure Zopfli for Low Iterations Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Use the Zopfli DEFLATE algorithm with a low number of iterations (e.g., 10) for faster compression while still benefiting from Zopfli's effectiveness. This is a good starting point for Zopfli. ```python import oxipng # Zopfli with low iterations (faster) oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.zopfli(10) ) ``` -------------------------------- ### StripChunks Usage Examples Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Illustrates various ways to use the StripChunks class with oxipng.optimize. Examples include keeping all chunks, stripping specific ones, keeping only certain ones, aggressive stripping, and safe stripping. ```python import oxipng # Keep all metadata oxipng.optimize("/path/to/image.png", strip=oxipng.StripChunks.none()) # Remove only text chunks oxipng.optimize( "/path/to/image.png", strip=oxipng.StripChunks.strip([b"tEXt", b"iTXt"]) ) # Remove all non-critical chunks except sRGB oxipng.optimize( "/path/to/image.png", strip=oxipng.StripChunks.keep([b"sRGB"]) ) # Remove all non-critical chunks (aggressive stripping) oxipng.optimize("/path/to/image.png", strip=oxipng.StripChunks.all()) # Safe stripping: preserves color space and dimension info oxipng.optimize("/path/to/image.png", strip=oxipng.StripChunks.safe()) ``` -------------------------------- ### Create PNG from Raw Pixels Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/README.md Create a PNG file from raw pixel data. This example demonstrates creating an RGBA image from NumPy array and optimizing the resulting PNG. Requires pixel data, width, and height. ```python import oxipng import numpy as np # Create 100x100 RGBA image width, height = 100, 100 pixels = np.random.randint(0, 256, (height, width, 4), dtype=np.uint8) # Convert to PNG raw = oxipng.RawImage(pixels.tobytes(), width, height) png_data = raw.create_optimized_png(level=6) with open("/output.png", "wb") as f: f.write(png_data) ``` -------------------------------- ### Real-Time Web Processing with libdeflater Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Use libdeflater for fast, real-time image optimization, suitable for web servers re-compressing assets on the fly. This example uses a moderate libdeflater level. ```python import oxipng # Fast for web servers or real-time processing oxipng.optimize( "/path/to/image.png", level=4, deflate=oxipng.Deflaters.libdeflater(6) ) ``` -------------------------------- ### Create PNG from PIL/NumPy with sRGB Profile Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RawImage.md Converts an image from PIL/NumPy to a PNG with an sRGB color profile. This example demonstrates adding a custom 'sRGB' chunk and using advanced compression options. ```python import oxipng from PIL import Image import numpy as np # Load an image with PIL img = Image.open("/path/to/image.jpg") # Convert to RGB and get as NumPy array rgb_array = np.array(img.convert("RGB"), dtype=np.uint8) height, width, channels = rgb_array.shape # Create RawImage with sRGB profile pixel_data = rgb_array.tobytes() raw = oxipng.RawImage( pixel_data, width, height, color_type=oxipng.ColorType.rgb(transparent_color=None) ) # Add sRGB chunk raw.add_png_chunk(b"sRGB", b"\0") # Optimize with maximum compression optimized = raw.create_optimized_png( level=6, deflate=oxipng.Deflaters.libdeflater(12) ) with open("/path/to/output.png", "wb") as f: f.write(optimized) ``` -------------------------------- ### Interlacing Usage Examples Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Demonstrates how to use the Interlacing enum with the oxipng.optimize function. Set to None to keep existing interlacing, Off to disable, or Adam7 to enable. ```python import oxipng # Keep existing interlacing oxipng.optimize("/path/to/image.png", interlace=None) # Disable interlacing oxipng.optimize("/path/to/image.png", interlace=oxipng.Interlacing.Off) # Enable Adam7 interlacing oxipng.optimize("/path/to/image.png", interlace=oxipng.Interlacing.Adam7) ``` -------------------------------- ### Override Preset Level Defaults in Pyoxipng Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Shows how to override default settings of a preset level by specifying individual options. This example customizes the filter choice for Level 2 optimization. ```python # Level 2 with custom filter choice oxipng.optimize( "/path/to/image.png", level=2, filter=[oxipng.RowFilter.NoOp, oxipng.RowFilter.Paeth] ) ``` -------------------------------- ### Asset Pipeline Optimization (Moderate) Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RowFilter.md Suitable for asset pipelines requiring moderate compression. This example uses a broader set of filters including Entropy and Brute, with a specified timeout. ```python oxipng.optimize( "/path/to/image.png", level=4, filter=[ oxipng.RowFilter.Paeth, oxipng.RowFilter.Entropy, oxipng.RowFilter.BigEnt, oxipng.RowFilter.Brute ], timeout=10.0 ) ``` -------------------------------- ### Create RGB PNG with Chroma Key Transparency Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/ColorType.md Generates an RGB PNG image where a specific RGB color (magenta in this example) is treated as transparent. This technique, known as chroma keying, is useful for creating images with a solid color background that should be removed. ```python import oxipng # Create RGB data with a specific "transparent" color width, height = 100, 100 # Create pixels: mostly green (0, 255, 0), some magenta (255, 0, 255) rgb_data = b'' for y in range(height): for x in range(width): if (x // 20 + y // 20) % 2 == 0: rgb_data += b'\xff\x00\xff' # Magenta (will be transparent) else: rgb_data += b'\x00\xff\x00' # Green (will be visible) # Set magenta as the transparent color color_type = oxipng.ColorType.rgb(transparent_color=(255, 0, 255)) raw = oxipng.RawImage(rgb_data, width, height, color_type=color_type) optimized = raw.create_optimized_png(level=6) with open("/path/to/rgb_with_key.png", "wb") as f: f.write(optimized) ``` -------------------------------- ### Create RawImage and Optimize PNG Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Instantiate RawImage with raw data, width, and height, then create an optimized PNG. Assumes 8-bit, row-major RGBA data by default. ```python raw = oxipng.RawImage(data, width, height) optimized_data = raw.create_optimized_png() ``` -------------------------------- ### Optimize PNG Image with Options Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Demonstrates how to use the `optimize` function with various keyword arguments to control the optimization process. This is useful for fine-tuning compression levels and applying specific optimizations. ```python oxipng.optimize("/path/to/image.png", level=6, fix_errors=True, interlace=oxipng.Interlacing.Adam7) ``` -------------------------------- ### Preset Levels for Pyoxipng Optimization Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Demonstrates using preset levels (0, 2, 6) for varying degrees of PNG compression. Level 0 is fastest with minimal optimization, while Level 6 offers maximum compression at the slowest speed. ```python import oxipng # Level 0: Fastest, minimal optimization oxipng.optimize("/path/to/image.png", level=0) # Level 2: Default, balanced optimization oxipng.optimize("/path/to/image.png", level=2) # Level 6: Maximum compression, slowest oxipng.optimize("/path/to/image.png", level=6) ``` -------------------------------- ### Initialize RowFilter List Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Shows how to create a list of `oxipng.RowFilter` enums to specify which filters to try during PNG optimization. This allows for granular control over the filtering algorithms applied. ```python oxipng.RowFilter.NoOp ``` ```python oxipng.RowFilter.Sub ``` ```python oxipng.RowFilter.Up ``` ```python oxipng.RowFilter.Average ``` ```python oxipng.RowFilter.Paeth ``` ```python oxipng.RowFilter.Bigrams ``` ```python oxipng.RowFilter.BigEnt ``` ```python oxipng.RowFilter.Brute ``` -------------------------------- ### Aggressive Compression for App Assets Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/StripChunks.md This snippet demonstrates aggressive compression by stripping all metadata and using Zopfli for deflation. It is ideal for app assets where the smallest possible file size is critical. ```python import oxipng # Strip everything for smallest file size oxipng.optimize( "/path/to/asset.png", level=6, strip=oxipng.StripChunks.all(), deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### Web Image Optimization (Fast Balance) Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RowFilter.md Use this configuration for general web images where a balance between compression and speed is desired. It employs basic filters like Paeth, Sub, and Up. ```python oxipng.optimize( "/path/to/image.png", level=2, filter=[ oxipng.RowFilter.Paeth, oxipng.RowFilter.Sub, oxipng.RowFilter.Up ] ) ``` -------------------------------- ### Fast Optimization Path with Simple Filters Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RowFilter.md Achieve quick compression by testing only simple filters. This is useful for scenarios where speed is prioritized over maximum compression. ```python import oxipng # Quick compression: test only simple filters oxipng.optimize( "/path/to/image.png", filter=[oxipng.RowFilter.NoOp, oxipng.RowFilter.Sub], fast_evaluation=True ) ``` -------------------------------- ### Maximum Compression Path with All Filters Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RowFilter.md Perform thorough optimization by trying all available filters and using Zopfli with a high level. This path aims for the best possible compression at the cost of time. ```python import oxipng # Thorough optimization: try all available filters oxipng.optimize( "/path/to/image.png", level=6, filter=[ oxipng.RowFilter.NoOp, oxipng.RowFilter.Sub, oxipng.RowFilter.Up, oxipng.RowFilter.Average, oxipng.RowFilter.Paeth, oxipng.RowFilter.MinSum, oxipng.RowFilter.Entropy, oxipng.RowFilter.Bigrams, oxipng.RowFilter.BigEnt, oxipng.RowFilter.Brute ], deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### Create Optimized PNG from RawImage Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/OVERVIEW.md Creates an optimized PNG file from a RawImage instance. Options can be passed as keyword arguments. ```Python optimized = raw.create_optimized_png(level=6, **opts) ``` -------------------------------- ### Create RawImage Instance Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/OVERVIEW.md Creates a RawImage instance from raw pixel data. Requires data, width, height, and optionally color type and bit depth. ```Python raw = RawImage(data, width, height, color_type=ct, bit_depth=8) ``` -------------------------------- ### Aggressive Optimization with Pyoxipng Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Applies maximum compression by removing metadata and performing extensive optimizations. Use this when file size is critical and metadata is not needed. ```python oxipng.optimize( "/path/to/image.png", level=6, strip=oxipng.StripChunks.all(), bit_depth_reduction=True, color_type_reduction=True, palette_reduction=True, grayscale_reduction=True, deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### Build Project with Maturin Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Build the Pyoxipng project using Maturin, which is used for building Rust-based Python extensions. ```sh maturin develop ``` -------------------------------- ### PyOxipng Module Initialization Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/EXPORTS.md This Rust code snippet demonstrates the initialization of the PyOxipng Python module using PyO3. It registers various types, including PngError, RowFilter, Interlacing, StripChunks, Deflaters, ColorType, and RawImage, as well as the optimize and optimize_from_memory functions. ```rust #[pymodule] fn oxipng(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("PngError", py.get_type::())?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_function(wrap_pyfunction!(optimize, m)?) m.add_function(wrap_pyfunction!(optimize_from_memory, m)?) Ok(()) } ``` -------------------------------- ### Pyoxipng Deflaters Factory Class Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/EXPORTS.md Selects the DEFLATE compression algorithm. Use 'libdeflater()' for general compression or 'zopfli()' for higher compression ratios at the cost of speed. ```python class Deflaters: @staticmethod def libdeflater(compression: int = 6) -> Deflaters @staticmethod def zopfli(iterations: int) -> Deflaters ``` -------------------------------- ### optimize() Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/INDEX.md Optimizes a PNG file on disk by writing the optimized version to a specified output path. ```APIDOC ## optimize() ### Description Optimizes a PNG file on disk by writing the optimized version to a specified output path. ### Method (Not specified, likely a Python function call) ### Endpoint (Not applicable, this is an SDK function) ### Parameters #### Path Parameters - **input_path** (Path) - Required - Path to the input PNG file. - **output_path** (Path) - Required - Path where the optimized PNG file will be saved. ### Response #### Success Response - None (modifies disk) ``` -------------------------------- ### Adaptive Compression Based on Image Size Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Dynamically selects between Zopfli and libdeflater based on image file size to balance compression and speed. Smaller files use Zopfli for better compression, while larger files use libdeflater for faster processing. ```python import oxipng import os def optimize_adaptive(input_file, output_file): # Use Zopfli for small images, libdeflater for large ones file_size = os.path.getsize(input_file) if file_size < 100_000: # < 100 KB deflater = oxipng.Deflaters.zopfli(150) elif file_size < 1_000_000: # < 1 MB deflater = oxipng.Deflaters.zopfli(50) else: deflater = oxipng.Deflaters.libdeflater(12) oxipng.optimize( input_file, output_file, level=6, deflate=deflater ) optimize_adaptive("/path/to/image.png", "/path/to/output.png") ``` -------------------------------- ### Optimize Image with Zopfli (Moderate Iterations) Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Uses the Zopfli algorithm with a moderate number of iterations, balancing compression and processing time. ```python # Zopfli with moderate iterations oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.zopfli(50) ) ``` -------------------------------- ### Basic PNG Optimization from Bytes Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/optimize_from_memory.md Reads PNG data from a file into bytes, optimizes it using default settings, and writes the optimized data to a new file. Ensure the input file path is correct. ```python import oxipng # Read PNG data from a file with open("/path/to/image.png", "rb") as f: png_data = f.read() # Optimize the data optimized = oxipng.optimize_from_memory(png_data) # Write optimized data to a new file with open("/path/to/image-optimized.png", "wb") as f: f.write(optimized) ``` -------------------------------- ### Conservative Optimization with Pyoxipng Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Performs optimization with minimal changes, ensuring metadata and color profiles are preserved. This is useful when you need to reduce file size without altering image integrity. ```python oxipng.optimize( "/path/to/image.png", level=1, strip=oxipng.StripChunks.none(), bit_depth_reduction=False, color_type_reduction=False, palette_reduction=False, grayscale_reduction=False ) ``` -------------------------------- ### RawImage Constructor Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RawImage.md Initializes a RawImage object from raw pixel data. This allows for the creation of PNG images from various raw formats. ```APIDOC ## RawImage Constructor ### Description Initializes a `RawImage` object from raw pixel data. This allows for the creation of PNG images from various raw formats. ### Signature ```python def __init__( data: bytes | bytearray, width: int, height: int, *, color_type: ColorType | None = None, bit_depth: int = 8 ) -> None ``` ### Parameters #### Constructor Parameters - **data** (`bytes | bytearray`) - Required - Raw pixel data. Format and size depend on `color_type` and `bit_depth`. Must have length matching width × height × bytes_per_pixel. - **width** (`int`) - Required - Image width in pixels. Must be a positive integer. - **height** (`int`) - Required - Image height in pixels. Must be a positive integer. - **color_type** (`ColorType | None`) - Optional - Specifies the pixel format. Defaults to `ColorType.rgba()` if not provided. - **bit_depth** (`int`) - Optional - Bits per color channel. Valid values: `1`, `2`, `4`, `8`, or `16`. Defaults to `8`. ### Raises - **oxipng.PngError**: The raw data is invalid or dimensions are incorrect. - **ValueError**: `bit_depth` is not one of the valid values (1, 2, 4, 8, 16). ``` -------------------------------- ### Configure Zopfli for Moderate Iterations Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Use the Zopfli DEFLATE algorithm with a moderate number of iterations (e.g., 100) to achieve a good balance between compression ratio and processing time. This offers better compression than lower iteration counts. ```python import oxipng # Zopfli with moderate iterations oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.zopfli(100) ) ``` -------------------------------- ### Override Level Preset with Strip Option Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Demonstrates how providing individual options like `strip` overrides the defaults set by the `level` parameter. Use this to fine-tune specific aspects of optimization beyond the preset. ```python oxipng.optimize( "/path/to/image.png", level=2, strip=oxipng.StripChunks.all() # Override level's strip default ) ``` -------------------------------- ### Configure Zopfli for Maximum Iterations Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Use the Zopfli DEFLATE algorithm with the maximum number of iterations (255) for the best possible compression. This option is very slow and should be used when file size is critical and processing time is not a concern. ```python import oxipng # Zopfli with maximum iterations (very slow, best compression) oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### Aggressive Lossy Optimization with Pyoxipng Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Applies aggressive optimization, allowing modifications to transparent pixels for maximum compression. All metadata is stripped, and Zopfli compression is used. ```python oxipng.optimize( "/path/to/image.png", level=6, optimize_alpha=True, # Allow modifying transparent pixels strip=oxipng.StripChunks.all(), # Remove all metadata deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### Release Assets with Zopfli Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Maximizes compression using Zopfli with a high iteration count, suitable for release builds where file size reduction is critical and execution time is less of a concern. ```python import oxipng # Maximize compression regardless of time (for release builds) oxipng.optimize( "/path/to/image.png", level=6, deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### RawImage Class Initialization Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/EXPORTS.md Initialize a RawImage object with raw pixel data, width, and height. Optional parameters include color_type and bit_depth for more specific image configurations. ```python class RawImage: def __init__( self, data: bytes | bytearray, width: int, height: int, *, color_type: ColorType | None = None, bit_depth: int = 8 ) -> None: pass ``` -------------------------------- ### oxipng.optimize Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/optimize.md Optimizes a PNG file on disk. It can either overwrite the input file or save the optimized version to a specified output path. Various optimization options can be passed as keyword arguments. ```APIDOC ## oxipng.optimize ### Description Optimizes a PNG file on disk with optional output to a separate file. ### Signature ```python def optimize(input: str | bytes | PathLike, output: str | bytes | PathLike | None = None, **kwargs) -> None ``` ### Parameters #### Parameters - **input** (`str | bytes | PathLike`) - Required - Path to the input PNG file to optimize. Can be a string path, bytes, or PathLike object. - **output** (`str | bytes | PathLike | None`) - Optional - Path where the optimized PNG will be written. If `None`, the input file is overwritten in place. - **kwargs** - Optional - Optimization options passed as keyword arguments. See [Configuration](../configuration.md) for all available options. ### Return Value Returns `None`. The function modifies files on disk as a side effect. ### Raises - **oxipng.PngError**: The input file is not a valid PNG or optimization fails (unless `fix_errors=True` is set) ### Examples #### Basic usage: optimize in place ```python import oxipng oxipng.optimize("""/path/to/image.png""") ``` #### Save to a new file ```python import oxipng oxipng.optimize("""/path/to/image.png""", """/path/to/image-optimized.png""") ``` #### Use custom optimization settings ```python import oxipng oxipng.optimize( """/path/to/image.png""", """/path/to/optimized.png""", level=6, deflate=oxipng.Deflaters.zopfli(255), fix_errors=True ) ``` #### Handle errors ```python import oxipng try: oxipng.optimize("""/path/to/image.png""") except oxipng.PngError as e: print(f"Optimization failed: {e}") ``` ``` -------------------------------- ### pyoxipng Architecture Diagram Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/OVERVIEW.md Illustrates the layered architecture of pyoxipng, showing the interaction between Python application code, the PyO3 extension module, and the oxipng Rust library. ```text ┌─────────────────────────────────────────┐ │ Python Application Code │ │ (uses oxipng module from Python) │ └──────────────┬──────────────────────────┘ │ ┌──────────────▼──────────────────────────┐ │ PyO3 Python Extension Module │ │ (Rust code compiled to .so/.pyd) │ │ │ │ ├─ lib.rs: Module setup & functions │ │ ├─ types.rs: Enums & factories │ │ ├─ options.rs: Argument parsing │ │ ├─ error.rs: Exception handling │ │ └─ raw.rs: RawImage & ColorType │ └──────────────┬──────────────────────────┘ │ ┌──────────────▼──────────────────────────┐ │ oxipng Rust Library (Dependency) │ │ (PNG optimization algorithms) │ └─────────────────────────────────────────┘ ``` -------------------------------- ### Clone Pyoxipng Repository Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Clone the Pyoxipng repository from GitHub and navigate into the project directory. ```sh git clone https://github.com/nfrasser/pyoxipng.git cd pyoxipng ``` -------------------------------- ### oxipng.RawImage Constructor Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Initializes a RawImage object with raw pixel data, dimensions, and optional color type and bit depth. ```APIDOC ## oxipng.RawImage Constructor ### Description Creates an optimized PNG file from raw image data. Assumes 8-bit, row-major RGBA by default. ### Parameters - **data** (bytes | bytearray) - Raw image data bytes. Format depends on `color_type` and `bit_depth` parameters. - **width** (int) - Width of raw image, in pixels. - **height** (int) - Height of raw image, in pixels. - **color_type** (oxipng.ColorType, optional) - Descriptor for color type. Defaults to `oxipng.ColorType.rgba()`. - **bit_depth** (int, optional) - Bit depth of raw image. Defaults to 8. ``` -------------------------------- ### oxipng.optimize Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Optimizes a PNG file on disk. It can either overwrite the input file or save the optimized version to a specified output path. ```APIDOC ## oxipng.optimize(input, output=None, **kwargs) ### Description Optimize a file on disk. ### Method Python Function ### Parameters #### Path Parameters - **input** (str | bytes | PathLike) - Required - path to input file to optimize - **output** (str | bytes | PathLike) - Optional - path to optimized output result file. If not specified, overwrites input. Defaults to None #### Keyword Arguments - **kwargs** - Accepts options for optimization. See [Options](#options). ### Returns - None ### Raises - **oxipng.PngError** – optimization could not be completed ### Examples: Optimize a file on disk and overwrite ```python oxipng.optimize("/path/to/image.png") ``` Optimize a file and save to a new location: ```python oxipng.optimize("/path/to/image.png", "/path/to/image-optimized.png") ``` ``` -------------------------------- ### Maximum Asset Compression (Final) Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RowFilter.md For final asset compression where maximum reduction is critical, this configuration uses an exhaustive set of filters and the Zopfli deflater. This is the slowest option. ```python oxipng.optimize( "/path/to/image.png", level=6, filter=[ oxipng.RowFilter.NoOp, oxipng.RowFilter.Sub, oxipng.RowFilter.Up, oxipng.RowFilter.Average, oxipng.RowFilter.Paeth, oxipng.RowFilter.MinSum, oxipng.RowFilter.Entropy, oxipng.RowFilter.Bigrams, oxipng.RowFilter.BigEnt, oxipng.RowFilter.Brute ], deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### Pyoxipng Deflater Error Handling Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Demonstrates how to handle potential ValueErrors when creating Zopfli deflaters with invalid iteration counts. Libdeflater levels are accepted within a wider range. ```python import oxipng # Valid zopfli iterations try: deflater = oxipng.Deflaters.zopfli(100) except ValueError: print("Error creating deflater") # Invalid: zopfli requires 1-255 iterations try: deflater = oxipng.Deflaters.zopfli(0) # Error! except ValueError as e: print(f"Invalid iterations: {e}") # Valid: libdeflater accepts any level deflater = oxipng.Deflaters.libdeflater(20) # Works (no range check) ``` -------------------------------- ### Batch Optimization with Moderate Zopfli Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Applies Zopfli compression with a moderate iteration count and a timeout for batch processing. This offers reasonable compression without extreme slowdowns. ```python import oxipng from pathlib import Path # Reasonable compression without extreme slowdown for png_file in Path("/path/to/images").glob("*.png"): oxipng.optimize( str(png_file), level=6, deflate=oxipng.Deflaters.zopfli(100), timeout=30.0 # 30 seconds per image ) ``` -------------------------------- ### Compare Interlaced vs. Non-Interlaced PNG File Size Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Interlacing.md This Python snippet demonstrates how to use pyoxipng to create and compare the file sizes of optimized PNG images with and without interlacing. It requires the `oxipng` library and assumes `pixel_data`, `width`, and `height` are defined. ```python import oxipng import os def get_file_size(data): return len(data) # Optimize without interlacing raw1 = oxipng.RawImage(pixel_data, width, height) non_interlaced = raw1.create_optimized_png(level=6, interlace=oxipng.Interlacing.Off) # Optimize with Adam7 interlacing raw2 = oxipng.RawImage(pixel_data, width, height) interlaced = raw2.create_optimized_png(level=6, interlace=oxipng.Interlacing.Adam7) print(f"Non-interlaced: {get_file_size(non_interlaced)} bytes") print(f"Interlaced: {get_file_size(interlaced)} bytes") print(f"Difference: {abs(get_file_size(interlaced) - get_file_size(non_interlaced))} bytes") print(f"Ratio: {get_file_size(interlaced) / get_file_size(non_interlaced):.2%}") ``` -------------------------------- ### Entropy-Based Heuristic Selection for Faster Filtering Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/RowFilter.md Utilize entropy heuristics for faster filter selection during PNG optimization. This method balances performance and compression by intelligently choosing filters. ```python import oxipng # Use entropy heuristic for faster selection oxipng.optimize( "/path/to/image.png", filter=[ oxipng.RowFilter.Entropy, oxipng.RowFilter.Paeth ], fast_evaluation=True ) ``` -------------------------------- ### RawImage() Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/INDEX.md Creates a RawImage instance from raw pixel data, allowing for manipulation and PNG creation. ```APIDOC ## RawImage() ### Description Creates a RawImage instance from raw pixel data, allowing for manipulation and PNG creation. ### Method (Not specified, likely a Python function call) ### Endpoint (Not applicable, this is an SDK function) ### Parameters #### Request Body - **pixel_data** (bytes) - Required - Raw pixel data. - **width** (int) - Required - Image width. - **height** (int) - Required - Image height. ### Response #### Success Response - **RawImage instance** - An instance of the RawImage class. ``` -------------------------------- ### RawImage.create_optimized_png() Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/INDEX.md Creates optimized PNG bytes from the RawImage instance, with optional keyword arguments for configuration. ```APIDOC ## RawImage.create_optimized_png() ### Description Creates optimized PNG bytes from the RawImage instance, with optional keyword arguments for configuration. ### Method (Not specified, likely a Python method call) ### Endpoint (Not applicable, this is an SDK method) ### Parameters #### Request Body - **kwargs** (dict) - Optional - Configuration options for optimization (e.g., level, filter, strip). ### Response #### Success Response - **optimized_png_bytes** (bytes) - The optimized PNG data in bytes. ``` -------------------------------- ### Optimize Image with Zopfli (High Iterations) Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Employs the Zopfli algorithm with a high iteration count for potentially better compression, though significantly slower. ```python # Zopfli with high iteration count (very slow, best compression) oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### Optimize Image with Libdeflater (Level 12) Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Uses the libdeflater algorithm for maximum compression, which is slower but yields better results. ```python # Maximum libdeflater compression (slower) oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.libdeflater(12) ) ``` -------------------------------- ### optimize_from_memory() Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/INDEX.md Optimizes PNG data in memory and returns the optimized PNG bytes. ```APIDOC ## optimize_from_memory() ### Description Optimizes PNG data in memory and returns the optimized PNG bytes. ### Method (Not specified, likely a Python function call) ### Endpoint (Not applicable, this is an SDK function) ### Parameters #### Request Body - **png_bytes** (bytes) - Required - The raw PNG data in bytes. ### Response #### Success Response - **optimized_bytes** (bytes) - The optimized PNG data in bytes. ``` -------------------------------- ### Error Handling for PNG Optimization Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/optimize_from_memory.md Demonstrates how to handle potential `oxipng.PngError` exceptions that may occur during PNG optimization due to invalid input data or other processing failures. This ensures graceful failure in your application. ```python import oxipng with open("/path/to/image.png", "rb") as f: png_data = f.read() try: optimized = oxipng.optimize_from_memory(png_data) except oxipng.PngError as e: print(f"Failed to optimize PNG: {e}") ``` -------------------------------- ### Configure libdeflater for Fast Compression Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Use the libdeflater DEFLATE algorithm for fast compression by setting the compression level to 0. This is useful when speed is prioritized over file size. ```python import oxipng # Fast compression (level 0) oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.libdeflater(0) ) ``` -------------------------------- ### Save RGB Image with Transparent Black Source: https://github.com/nfrasser/pyoxipng/blob/main/README.md Load an RGB image, convert it to raw bytes, and create an optimized PNG with black pixels set as transparent. Requires Pillow and NumPy. ```python from PIL import Image import numpy as np # Load an image file with Pillow jpg = Image.open("/path/to/image.jpg") # Convert to RGB numpy array rgb_array = np.array(jpg.convert("RGB"), dtype=np.uint8) height, width, channels = rgb_array.shape # Create raw image with sRGB color profile data = rgb_array.tobytes() color_type = oxipng.ColorType.rgb((0, 0, 0)) # black is transparent raw = oxipng.RawImage(data, width, height, color_type=color_type) raw.add_png_chunk(b"sRGB", b"\0") # Optimize and save optimized = raw.create_optimized_png(level=6) with open("/path/to/image/optimized.png", "wb") as f: f.write(optimized) ``` -------------------------------- ### Optimize PNG In-Place Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/optimize.md Optimize a PNG file directly, overwriting the original. Ensure the input path is correct. ```python import oxipng # Optimize a PNG file in place, overwriting the original oxipng.optimize("/path/to/image.png") ``` -------------------------------- ### Configure libdeflater for Maximum Compression Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Use the libdeflater DEFLATE algorithm for maximum compression by setting the compression level to 12. Be aware that this option is the slowest. ```python import oxipng # Maximum compression (level 12, slow) oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.libdeflater(12) ) ``` -------------------------------- ### optimize() Function Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/COMPLETION_SUMMARY.txt Optimizes a PNG file at the given path. This function provides a direct way to optimize a file on disk. ```APIDOC ## optimize() ### Description Optimizes a PNG file at the specified file path. ### Method Not applicable (Python function) ### Parameters #### Path Parameters - **path** (str) - Required - The file path to the PNG image to be optimized. #### Query Parameters None #### Request Body None ### Request Example ```python from pyoxipng import optimize optimize("path/to/your/image.png") ``` ### Response #### Success Response This function does not return a value upon successful completion. It modifies the file in place or creates a new optimized file depending on configuration. #### Response Example None (operates via side effects on the file system) ``` -------------------------------- ### Optimize PNG to New File Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/optimize.md Optimize a PNG file and save the result to a specified output path. This preserves the original file. ```python import oxipng # Optimize and save to a different location oxipng.optimize("/path/to/image.png", "/path/to/image-optimized.png") ``` -------------------------------- ### Optimize PNG with Custom Settings Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/optimize.md Optimize a PNG file using custom compression level and deflate algorithm. The `fix_errors=True` option can be used to attempt optimization even with minor PNG errors. ```python import oxipng # Optimize with custom compression level and deflate algorithm oxipng.optimize( "/path/to/image.png", "/path/to/optimized.png", level=6, deflate=oxipng.Deflaters.zopfli(255), fix_errors=True ) ``` -------------------------------- ### Type Annotated PNG Creation from Pixels Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/EXPORTS.md Provides type hints for creating an optimized PNG from raw pixel data. Specify width, height, and optionally color type. ```python from oxipng import ( optimize, optimize_from_memory, RawImage, ColorType, RowFilter, Interlacing, StripChunks, Deflaters, PngError, ) from pathlib import Path from typing import Optional, Sequence def create_from_pixels( pixels: bytes, width: int, height: int, color_type: ColorType | None = None ) -> bytes: raw = RawImage(pixels, width, height, color_type=color_type) return raw.create_optimized_png(level=6) ``` -------------------------------- ### Fast Pyoxipng Optimization for Batch Processing Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/configuration.md Configures Pyoxipng for fast evaluation and sets a timeout for processing numerous images efficiently. This is ideal for batch operations where speed is a priority. ```python oxipng.optimize( "/path/to/image.png", level=2, fast_evaluation=True, timeout=5.0 # 5 seconds maximum ) ``` -------------------------------- ### Build-Time Asset Compression with libdeflater Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Balances compression and build time by using libdeflater with a higher compression level and a timeout. This is suitable for build pipelines with moderate time constraints. ```python import oxipng # Balance between compression and build time oxipng.optimize( "/path/to/image.png", level=6, deflate=oxipng.Deflaters.libdeflater(12), timeout=10.0 # 10 second limit ) ``` -------------------------------- ### Optimize a PNG File Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/README.md Optimize a PNG file using default settings or custom parameters like output location and compression level. Requires the input file path. ```python import oxipng # Simple optimization with defaults (level 2) oxipng.optimize("/path/to/image.png") # Custom output location oxipng.optimize("/input.png", "/output.png") # With custom settings oxipng.optimize( "/input.png", "/output.png", level=6, deflate=oxipng.Deflaters.zopfli(255) ) ``` -------------------------------- ### oxipng.optimize_from_memory Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/optimize_from_memory.md Optimizes PNG data that is already loaded in memory as bytes. This function takes raw PNG data as bytes and returns the optimized PNG data as bytes. It supports various optimization options that can be passed as keyword arguments. ```APIDOC ## optimize_from_memory(data: bytes, **kwargs) -> bytes ### Description Optimize PNG data that is already loaded in memory as bytes. This function takes raw PNG data as bytes and returns the optimized PNG data as bytes. It supports various optimization options that can be passed as keyword arguments. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **data** (bytes) - Required - Raw PNG file data as bytes. Must be a valid PNG format. - **kwargs** (Options) - Optional - Optimization options passed as keyword arguments. See [Configuration](../configuration.md) for all available options. ### Request Example ```python import oxipng with open("/path/to/image.png", "rb") as f: png_data = f.read() optimized = oxipng.optimize_from_memory(png_data) with open("/path/to/image-optimized.png", "wb") as f: f.write(optimized) ``` ### Response #### Success Response (bytes) - Returns `bytes` containing the optimized PNG data. The output can be directly written to a file or transmitted over a network. #### Response Example ```python # Example of returned bytes (actual content will be binary PNG data) optimized_png_bytes = b'\x89PNG\r\n\x1a\n...' ``` ### Raises - **oxipng.PngError**: The input data is not a valid PNG or optimization fails (unless `fix_errors=True` is set). ``` -------------------------------- ### Import oxipng Module Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/EXPORTS.md Import the oxipng module for use in your Python scripts. ```python import oxipng ``` -------------------------------- ### Optimize PNG File Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/OVERVIEW.md Optimizes a PNG file from disk to disk. Requires input and output file paths. Options can be passed as keyword arguments. ```Python oxipng.optimize("/input.png", "/output.png", level=6, **opts) ``` -------------------------------- ### Basic PNG Optimization Error Handling Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/errors.md Use a simple try-except block to catch PngError during basic image optimization. This is useful for handling individual file processing failures. ```python import oxipng try: oxipng.optimize("/path/to/image.png", "/path/to/output.png") except oxipng.PngError as e: print(f"Failed to optimize PNG: {e}") # Handle the error: log it, skip the image, etc. ``` -------------------------------- ### Configure libdeflater for Balanced Compression Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/api-reference/Deflaters.md Use the libdeflater DEFLATE algorithm with the default compression level (6) for a balance between speed and compression. This is suitable for general-purpose image optimization. ```python import oxipng # Balanced compression (level 6, default) oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.libdeflater(6) ) ``` -------------------------------- ### Optimize Image with Libdeflater (Level 6) Source: https://github.com/nfrasser/pyoxipng/blob/main/_autodocs/types.md Uses the libdeflater algorithm for fast, real-time image optimization with a compression level of 6. ```python import oxipng # Fast compression with libdeflater level 6 oxipng.optimize( "/path/to/image.png", deflate=oxipng.Deflaters.libdeflater(6) ) ```