Skip to content

Instantly share code, notes, and snippets.

@prcaen
Created May 13, 2015 12:42
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prcaen/eb039d63f34e76d93656 to your computer and use it in GitHub Desktop.
Save prcaen/eb039d63f34e76d93656 to your computer and use it in GitHub Desktop.
Compress all PNG or JPG files of a folder thanks to TinyPNG or TinyJPG API
#!/bin/bash
# Install
# This script need a API key from TinyPNG. See this page: https://tinypng.com/developers
# It also need jq library, which can be install thanks to: `brew install jq`
# Usage
# cd to your folder. This script will compress all PNG or JPG files recursively.
API_KEY="CHANGE_ME"
if [ $API_KEY = "CHANGE_ME" ]
then
echo "CHANGE THE API_KEY in this file."
exit 1
fi
if ! type "jq" > /dev/null
then
echo "Please install `jq`"
exit 1
fi
find . -type f \( -name \*.jpg -o -name \*.png -o -name \*.jpeg \) -print0 | while IFS= read -r -d '' file; do
echo "Compress file: $file"
json=$(curl -sS --user api:$API_KEY --data-binary @$file https://api.tinypng.com/shrink)
url=$(jq -n "$json.output.url" | sed -e 's/^"//' -e 's/"$//')
echo "Compression OK. Old size: $(jq -n "$json.input.size"), new size: $(jq -n "$json.output.size"), ratio: $(jq -n "$json.output.ratio")"
echo "Downloading the compressed file…"
curl -sS $url > $file
echo "Compressed file downloaded with success!"
done
@ErwannRobin
Copy link

Added the support of filename with blank characters : https://gist.github.com/Diwann/aefcb54e205bc531a9de

@Rubueno
Copy link

Rubueno commented Apr 2, 2024

I found oxipng to be very useful for this task.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment