All posts

Compress PNG via CLI

Lossless PNG compression with optipng and metadata stripping.

Open online converter

Packages to install

Install optipng — it tries Deflate settings and shrinks PNG without changing pixels.

optipng
apt install
sudo apt-get update
sudo apt-get install -y optipng

How to run the command

optipng -o2 balances speed and size, -strip all removes EXIF and text chunks, and -out writes a new file.

optipng
optipng -o2 -strip all -out photo.min.png photo.png

Dockerfile example

Build a minimal Ubuntu image with the required packages and run the conversion inside the container.

Dockerfile
FROM ubuntu:24.04

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        optipng && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /work
docker build && docker run
docker build -t compress-png .
docker run --rm -v "$PWD:/work" -w /work compress-png \
  optipng -o2 -strip all -out photo.min.png photo.png

Example commands

Run these locally after installing the packages, or inside the container from the Dockerfile.

Example 1
optipng -o2 -strip all -out photo.min.png photo.png
Example 2
optipng -o3 -strip all -out photo.min.png photo.png