How to Compress PNG File Size with ImageMagick?

Reducing the file size of PNG images is crucial for optimizing website performance and saving storage space. ImageMagick’s versatile convert command provides several powerful techniques to compress PNGs without sacrificing essential visual quality. This article covers the most effective methods to shrink PNG files, including adjusting quality settings, stripping metadata, changing bit depth, and utilizing external compression libraries directly through the command line.


Basic PNG Compression Using Quality Settings

Unlike JPEGs, where the -quality flag directly changes the lossy compression level, PNG quality settings in ImageMagick operate differently. For PNGs, the quality digital value represents a combination of the compression filter type (0 to 4) and the zlib compression level (0 to 9).

To apply maximum standard compression, you can use a quality setting of 95 (which uses adaptive filtering and maximum zlib compression):

convert input.png -quality 95 output.png

Stripping Metadata to Reduce Size

PNG files often contain hidden metadata, such as camera profiles, timestamps, color profiles, and text comments. This data adds to the file size without affecting the visible image. You can safely strip this information using the -strip flag:

convert input.png -strip output.png

Combining -strip with the -quality flag is one of the quickest ways to achieve a smaller file size:

convert input.png -strip -quality 95 output.png

Converting PNG to Index Color (PNG8)

Standard PNGs are usually saved in 24-bit or 32-bit true color (PNG24 or PNG32). If your image consists of simple graphics, logos, or screenshots that do not require millions of colors, you can drastically reduce the file size by converting it to an 8-bit indexed PNG (PNG8). This limits the image to a maximum of 256 colors.

convert input.png png8:output.png

Applying Lossy Color Reduction

If you want to keep the image in a standard PNG format but want aggressive file size savings, you can force ImageMagick to reduce the number of unique colors using the -colors flag. This introduces a small, often unnoticeable amount of lossy compression.

convert input.png -colors 256 -strip output.png

Integrating ImageMagick with External Compressors

For the absolute best results, ImageMagick can delegate the compression to specialized PNG optimization tools like pngcrush, optipng, or advpng if they are installed on your system. You can invoke these via the -define flag:

convert input.png -define png:compression-level=9 -define png:compression-strategy=1 output.png

By combining these flags—stripping metadata, optimizing the zlib compression level, and choosing the correct color depth—you can drastically shrink your PNG assets using a single ImageMagick command line.