Optimize images without quality loss in Rust with Oxipng

Fast-loading pages feel snappy, consume less bandwidth, and rank better in search—yet images are often the heaviest assets on a site. Lossless image optimization fixes that without degrading visual quality. In this DevTip, you’ll learn how to achieve it with Oxipng, a blazing-fast Rust tool for PNG compression.
Why image optimization matters
Reducing image file sizes leads to quicker load times, lower bandwidth bills, and better Core Web Vitals. When the compression is lossless, you keep pixel-perfect fidelity, which is critical for UI assets, icons, and archival graphics.
Oxipng: fast and efficient PNG optimization
Oxipng is a Rust-based optimizer that improves upon legacy utilities such as OptiPNG by taking advantage of modern concurrency and algorithmic tweaks.
Key features
- Lossless PNG compression
- Multithreading for near-linear speedups on multi-core CPUs
- Automated heuristics that pick optimal settings
- Simple CLI and library APIs for easy automation
- Significant size reductions (often 20-40%) with zero quality loss
System requirements
- Rust 1.74.0 or newer (for building from source)
- Building without the
--release
flag can be very slow; prefer release builds for production use
Install Oxipng
You can install Oxipng using Rust's package manager or common system package managers:
# Via cargo (rust's package manager)
cargo install oxipng
# Via package managers
# For Ubuntu/Debian
apt-get install oxipng
# For macOS (using homebrew)
brew install oxipng
Optimize a single PNG
oxipng -o 4 image.png
The -o
flag sets the optimization level (0–6). Higher levels try harder to squeeze out extra
bytes, which takes more CPU time. Level 4 is often a good balance.
Enable multithreading
Oxipng can use multiple CPU cores to speed up optimization, especially useful for batch processing.
# Use all available logical cores
oxipng -o 4 -P image.png
Performance snapshot
Oxipng is designed for speed. Here are some benchmarks run on an Intel Core i7-12700:
oxipng -P ≈ 60 ms
oxipng -o4 -P ≈ 89 ms
This speed makes it practical to integrate into automated workflows like commit hooks or CI/CD pipelines without causing significant delays.
Advanced usage
Batch-process a folder
You can combine find
with oxipng
to optimize all PNG files within a directory and its
subdirectories:
find ./images -name "*.png" -exec oxipng -o 4 -P {} +
This command finds all files ending in .png
within the ./images
directory and runs oxipng
on
them using multiple cores (-P
) at optimization level 4 (-o 4
).
Preserve metadata
By default, Oxipng strips ancillary chunks like EXIF data or color profiles to save space. If you need to keep this metadata:
oxipng -o 4 --preserve image.png
Embed Oxipng in your Rust code
You can also use Oxipng as a library within your Rust applications. First, add it as a dependency in
your Cargo.toml
:
[dependencies]
oxipng = "9.0" # Check crates.io for the latest version
Then, you can call its optimization functions programmatically:
use oxipng::{optimize, InFile, OutFile, Options};
use std::path::PathBuf;
fn main() -> Result<(), oxipng::PngError> {
let input_path = PathBuf::from("input.png");
// Specify output path or use OutFile::None to overwrite the input file
let output_path = OutFile::Path(Some(PathBuf::from("output.png")));
// Use optimization level 4
let options = Options::from_preset(4);
match optimize(&InFile::Path(input_path), &output_path, &options) {
Ok(_) => println!("Optimization successful!"),
Err(e) => eprintln!("Optimization failed: {}", e),
}
Ok(())
}
This example optimizes input.png
using preset level 4 and saves the result to output.png
. Error
handling is included for robustness.
Real-world applications
- Web development: Automatically optimize PNG assets during the build process for faster websites.
- Game development: Reduce the size of texture atlases and UI elements without visual loss.
- CI/CD pipelines: Add an optimization step to ensure all committed PNGs are compressed.
- Content Management Systems (CMS): Integrate Oxipng to optimize user-uploaded images on the fly.
Use Transloadit for multi-format optimization
While Oxipng is excellent for PNGs, you might need a solution that handles various formats like JPEG, GIF, WebP, and SVG. Transloadit's 🤖 /image/optimize Robot provides efficient image optimization supporting these formats. It can reduce file sizes significantly (often up to 80%) while maintaining visual quality, automatically handling format detection and optimization settings. It integrates easily via REST API or SDKs.
Whether you integrate Oxipng directly into your Rust projects or use a hosted service like Transloadit for broader format support, lossless image optimization is a straightforward way to improve performance. Give Oxipng a try and make your PNGs leaner today.