Skip to content

How to optimize images from command line

I’m using the following tools to perform lossless image compression:

jpegoptim – jpegoptim is a utility for optimizing JPEG files. It provides lossless optimization (based on optimizing the Huffman tables) and “lossy” optimization based on setting a maximum quality factor.
optipng – OptiPNG is a PNG optimizer that recompresses the image files to a smaller size without losing any data. It works in a manner similar to pngcrush, but it has a wider automatic search space (leading to possibly a better compression), and it runs faster.

I have created a bash function in my ‘~/.bashrc’ file:

function optimgs() {
	if [ $# -eq 0 ]
		then
		echo "Use: optimgs path"
		echo "Example: optimgs /var/www"
	else
        	echo "Optimize jpg/jpeg images ....."
        	for i in `find $1 -type f -name *.jpg` ; do jpegoptim $i ; done
        	echo "Optimize png images ....."
        	for i in `find $1 -type f -name *.png` ; do optipng $i ; done
	fi
}

** You must do ‘source ~/.bashrc’ after modifications.

Quick usage:

optimgs /path/to/img_dir
optimgs /var/www
Published inLinux