· 2 years ago · Mar 04, 2023, 06:50 PM
1#!/bin/bash
2# Install
3# This script need a API key from TinyPNG. See this page: https://tinypng.com/developers
4# It also need jq library, which can be install thanks to: `brew install jq`
5
6# Usage
7# cd to your folder. This script will compress all PNG or JPG files recursively.
8
9API_KEY="API_KEY_YOUR"
10RED="\033[0;31m"
11GREEN="\033[0;32m"
12NORMAL="\033[0m"
13
14if [ $API_KEY = "CHANGE THE API_KEY" ]
15then
16 echo "YES. CHANGE THE API_KEY in this file."
17 exit 1
18fi
19
20if ! type "jq" > /dev/null
21then
22 echo "Please install `jq`"
23 exit 1
24fi
25
26find . -type f \( -name \*.jpg -o -name \*.png -o -name \*.jpeg \) -print0 | while IFS= read -r -d '' file; do
27 echo "Compress file: $file"
28
29 json=$(curl -sS --user api:$API_KEY --data-binary @"$file" https://api.tinypng.com/shrink)
30 url=$(jq -n "$json.output.url" | sed -e 's/^"//' -e 's/"$//')
31
32 echo -e "Compression OK. Old size: $(jq -n "$json.input.size"), new size: $(jq -n "$json.output.size"), ratio: ${GREEN} $(jq -n "$json.output.ratio")${NORMAL}"
33 echo "Downloading the compressed file…"
34
35 curl -sS $url > "$file"
36
37 echo "Compressed file downloaded with success!"
38done
39