Using Tinypng to optimize images from the command line
Our team has identified image optimization as one of the more time consuming and often forgotten steps of our current process. In the long run we want to automate it using a git pre-commit hook. As the first step to this I’ve got PNG and JPG optimization working manually using TinyPNG from the command line:
git diff --diff-filter=ACM --name-only HEAD | grep ".png\|.jpg" | xargs tinypng
To set this up:
- Get a TinyPNG API key.
- Save the API key in a file named
.tinypngin your home directory.
- Install the npm TinyPNG CLI.
Because it’s not part of our site yet I installed it globally:
npm install -g tinypng-cli
- Add the files you want to optimize to Git’s staging area. (
git add *will add all the files you’ve edited)
git diff --diff-filter=ACM --name-only HEAD | grep ".png\|.jpg" | xargs tinypng.
- Add add the new modified files to your Git staging area before committing.
What it’s doing:
- Telling Git we want to a list of differences between two things
- Filtering what we want to compare to include only Additions, Changes, and Modifications
- Asking for just the file names instead of the full output.
- One of the two things we’re comparing is the files in the staging area. Specifying
HEADhere says to compare them to the files in the most recent commit.
- This is a “pipe”, it passes the results of the Git diff to the next command.
- Grep is a command line search tool.
- I’m using grep to find only the files with .png or .jpg file extensions.
- Another pipe to pass our reduced list of files on to the next step.
- This is the results of the grep. (Why it goes here instead of after the next command I do not know.)
- Finally we get tinypng to do its magic. The compressed files will replace the originals.