DEV Community

loading...

PNG optimization from the command line

paramagicdev profile image Konnor Rogers Originally published at blog.konnor.site Updated on ・2 min read

Installation

First step...install pngquant

If you're on MacOS, simply do:

brew install pngquant
Enter fullscreen mode Exit fullscreen mode

If you're not on MacOS, please refer to the pngquant homepage for installation instructions.

https://pngquant.org/

Running pngquant

The next step is to run pngquant on all your files you wish to optimize.

For example, if I have my .png files in my app/assets/images
directory, I would do the following:

cd app/assets/images

# Grab all png's by recursing through current directory.
# Quality and speed can be adjusted to personal needs.
# this is what I use.
pngquant ./**/*.png --quality 65-80 --speed 1
Enter fullscreen mode Exit fullscreen mode

This will generate a bunch of files with the -fs8.png suffix like so:

.
├── file-1.png
├── file-1-fs8.png
├── file-2.png
├── file-2-fs8.png
├── file-3.png
├── file-3-fs8.png
├── file-4.png
└── file-4-fs8.png
Enter fullscreen mode Exit fullscreen mode

Im sure theres a way to have pngquant overwrite your files, but this
lets me do an easy comparison of before / after sizes. Then I'll rename
the newly optimized files to overwrite their original file.

Bash Command

This is the command I use to rewrite all my newly optimized images to
overwrite their parent. Use with caution :)

for FILE in ./**/*-fs8.png; do original=${FILE%%-fs8.png}; mv "$FILE" "$original.png"; done
Enter fullscreen mode Exit fullscreen mode

Pulling it all together

Quick easy command to do it all at once.

pngquant ./**/*.png --quality 65-80 --speed 1
for FILE in ./**/*-fs8.png; do original=${FILE%%-fs8.png}; mv "$FILE" "$original.png"; done
Enter fullscreen mode Exit fullscreen mode

By using this method, I managed to get my ~2-4mb PNGs in a site I'm working on down to ~100-400kb.

Good luck and may your png files be forever optimized!

Discussion (0)

pic
Editor guide