Images take up way too much space!
Hi everyone!
Every so often I've found myself having to optimize the media folder of a website, usually wordpress or ghost cms.
My partners in crime are two shell commands, jpegoptim and optipng.
By combining the find command with these two tools, you can shrink the files of an entire folder and its subfolders.
Below are a couple of handy examples where I'll explain the various parameters used.
JPEG reduction
To shrink jpg and jpeg images we'll use jpegoptim.
Installation
Debian and derivatives:
apt-get install jpegoptim
RPM and derivatives
yum install epel-release
dnf install epel-release [ Fedora 22 + ]
yum install jpegoptim
dnf install jpegoptim [ Fedora 22 + ]
MacOS
brew install jpegoptim
Usage
Once you're in the folder you're interested in, you can run the command with:
find . -name "*.jpeg" -exec jpegoptim --strip-all --all-progressive --size = 250k { } \ ;
In this command we're passing 3 parameters, and asking find to find, in the current folder and its subfolders, all the files matching *.jpeg
--strip-all this directive removes all the image metadata, like the ones an iphone adds when you take a photo (gps location, etc)
--all-progressive Changes the compression from baseline to progressive (here's a good explanation of the difference https://www.liquidweb.com/kb/what-is-a-progressive-jpeg/ )
--size=250k forces the maximum size to 250k
PNG reduction
For this kind of reduction, instead, we'll use optipng.
Installation
Debian and derivatives:
apt-get install optipng
RPM and derivatives
yum install epel-release
dnf install epel-release [ Fedora 22 + ]
yum install optipng
dnf install optipng [ Fedora 22 + ]
MacOS
brew install optipng
Usage
Once you're in the folder you're interested in, you can run the command with:
find . -name "*.png" -exec optipng -o7 -strip all { } \ ;
-o7 is the parameter that sets how many passes are made to optimize the image. I won't go into too much detail, but you can get lossless compression of up to 30%
-strip all just like for the jpeg optimization, we remove the metadata
Sources and further reading: