optipng: Lossless PNG Optimization in CI
optipng -o2 image.png recompresses a PNG losslessly in place to make it smaller without changing a pixel.
optipng is the standard lossless PNG optimizer in build pipelines. It rewrites the file in place, so the optimization level and the -strip flag are what you tune.
What it does
optipng tries different PNG filter and zlib compression strategies and keeps the smallest result, with no loss of image data. Higher -o levels search harder (slower) for a smaller file. -strip all also removes ancillary chunks like metadata.
Common usage
# default-ish optimization in place
optipng -o2 image.png
# maximum effort plus metadata removal
optipng -o7 -strip all image.png
# write to a new file, keep the original
optipng -o2 -out small.png image.png
# batch a directory
optipng -o2 *.pngOptions
| Flag | What it does |
|---|---|
| -o<0-7> | Optimization level (higher = smaller, slower; default -o2) |
| -strip all | Remove all ancillary chunks (metadata) |
| -out <file> | Write to a new file instead of in place |
| -fix | Try to repair broken/CRC-error PNGs |
| -clobber | Overwrite an existing -out file |
| -quiet | Suppress progress output |
In CI
Use -o2 for fast builds and reserve -o7 for a release step, since high levels can be very slow on large images. optipng overwrites in place by default, so commit the optimized assets or run it as a build artifact step, not on source you need pristine.
Common errors in CI
"optipng: command not found" means it is not installed; apt-get install -y optipng. "Error: Not a PNG file" means the input is actually a JPEG/GIF (optipng only handles PNG; convert first). If a PNG is already optimal, optipng prints "is already optimized" and leaves it unchanged, which is not an error. Corrupt PNGs report a CRC/IDAT error; -fix may recover them.