François was even kind enough to include a screenshot with the savings I missed out on.
I used to have a workflow where I ran every image through ImageOptim to compress them as much as possible. But it’s a manual step that’s too easy to ignore.
So here’s a way to automate it. These couple of scripts automatically run and compress your files for you, so you don’t have to think about them ever again. They use the optipng tool in the background.
You start by installing the
On Red Hat or CentOS:
$ yum install optipng
On Ubuntu / Debian:
$ apt-get install optipng
Now, let’s automate this.
Automatically optimise your images every hour
Friendly reminder: before running any of these tools, make sure you have a back-up to restore from!
optipng tool itself works pretty simple. The most basic command is
optipng image.png , which optimises the image called ‘image.png’ and replaces it on your server (so you lose the original!).
We can add some additional parameters that further reduce the size, increase the compression ratio and strip all META info from the PNG file you don’t need. Here’s my current command for the most optimal size.
$ optipng -o7 -f4 -strip all -quiet image.png
This takes the file called ‘image.png’, runs all sorts of optimisations over it, strips meta data and overwrites the file with the new and improved version.
Now, to run this automatically on your server, all you need is the following cronjob. Let this run every hour, and it’ll take all PNG files created in the last hour and optimises them for you.
$ find htdocs/wp-content/ -cmin -60 -name '*.png' | xargs optipng -o7 -f4 -strip all -quiet
This essentially does these things:
- Find all *.png files in the ‘htdocs/wp-content’ directory that were created in the last hour (this is the directory where WordPress uploads its content)
- For each of those found files, run the
optipngcommand on them
Add that to your crontab and you never have to think about it again.
$ crontab -l 0 * * * * find ~/htdocs/wp-content/ -cmin -60 -name '*.png' | xargs optipng -o7 -f4 -strip all -quiet
Optimise all your existing images
If you’re only thinking about activating this after you have a bunch of files, you may want to run this tool over all your images — not just the ones modified in the last hour.
I’ll repeat myself, but here it goes: before you run this over all your files, have a back-up! These settings replace the original file, so you no longer have the original.
$ find ~/htdocs/wp-content/ -name '*.png' | xargs optipng -o7 -f4 -strip all -quiet
That command searches for all ‘*.png’ files in the
~/htdocs/wp-content/ folder and runs the
optipng command over all of them.
转载本站任何文章请注明：转载至神刀安全网，谢谢神刀安全网 » Optimize the size of .PNG images automatically on your webserver with optipng