tinypng.sh 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/bin/bash
  2. if [ -z "$1" ] || [ -z "$2" ] || [ ! -d "$1" ] ; then
  3. printf "Usage: $0 <Directory to Search> <File Expression>\n"
  4. printf "\tex. tinypng.sh . 'thumb*.jpg' // All JPG thumbnails in current directory\n"
  5. printf "\tex. tinypng.sh subdirectory/ '*.png' // All PNG files under subdirectory\n"
  6. exit 1
  7. fi
  8. APIKEY="INSERT_API_KEY_HERE"
  9. LOGFILE="tinypng.log"
  10. # Find all jpg/png files with names starting with 'thumb*' (thumbnails)
  11. FILES="$(find $1 -type f -name $2)";
  12. for FILE in $FILES ; do
  13. # Prepend './' if directory was given (to match output from '.')
  14. if [ "$1" != "." ] ; then
  15. FILE="./$FILE"
  16. fi
  17. # Sanity check to ensure file exists
  18. if [ -e "$FILE" ] ; then
  19. # Check if the file has been compressed previously
  20. if [ -e "$LOGFILE" ] && (grep -Fxq "$FILE" "$LOGFILE") ; then
  21. printf "$FILE has already been compressed\n"
  22. continue
  23. fi
  24. # Upload file to tinypng compression service
  25. printf "Uploading $FILE..\n"
  26. JSON=`curl --progress-bar https://api.tinypng.com/shrink --user api:$APIKEY --data-binary @"$FILE"`
  27. URL=`echo $JSON | grep -oP 'url\":\"\K.+(?=")'`
  28. RATIO=`echo $JSON | grep -oP 'ratio\":\K.+(?=,)'`
  29. # Download replacement if URL is given
  30. if [ -n "$URL" ] ; then
  31. printf "URL: $URL\n"
  32. printf "Downloading replacement $FILE..\n"
  33. curl --progress-bar $URL > "$FILE"
  34. printf "${FILE} is $RATIO%% smaller than the original\n"
  35. printf "$FILE\n" >> "$LOGFILE"
  36. fi
  37. printf "\n"
  38. fi
  39. done
  40. unset -v APIKEY
  41. unset -v LOGFILE
  42. unset -v JSON
  43. unset -v URL
  44. unset -v RATIO