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 to use multiple CPU cores
- Automated heuristics that pick optimal settings
- Simple CLI and library APIs for easy automation
- Size reductions that depend on the image and its existing compression
System requirements
- Rust 1.74.0 or newer (for building from source)
- Building without the
--releaseflag 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
# On distributions that provide an oxipng package (otherwise use cargo above)
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.
Control multithreading
Oxipng uses multiple CPU cores by default. Limit the thread count when sharing a build machine:
# Use at most four threads
oxipng -o 4 --threads 4 image.png
Use --pretend (-P) to measure potential savings without writing files. Benchmark your own
assets before choosing an optimization level for commit hooks or CI/CD.
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 -type f -name "*.png" -exec oxipng -o 4 {} +
This command finds all files ending in .png within the ./images directory and runs oxipng on
them at optimization level 4 (-o 4). This modifies the files in place; keep a backup of originals.
Preserve metadata
Oxipng does not request metadata stripping by default. --preserve instead preserves file
permissions and timestamps where possible. To retain those file attributes:
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");
// OutFile::None performs a dry run; from_path writes to a separate file.
let output_path = OutFile::from_path(PathBuf::from("output.png"));
// Use optimization level 4
let options = Options::from_preset(4);
optimize(&InFile::Path(input_path), &output_path, &options)?;
println!("Optimization successful!");
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.
