image-optimization.sh 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env bash
  2. set -e
  3. OPTIPNG=$(which optipng)
  4. if ! [ -x "$OPTIPNG" ]; then
  5. echo "optipng executable not found, please install" >&2
  6. exit 1
  7. fi
  8. JPEGOPTIM=$(which jpegoptim)
  9. if ! [ -x "$JPEGOPTIM" ]; then
  10. echo "jpegoptim executable not found, please install" >&2
  11. exit 2
  12. fi
  13. SCOUR=$(which scour)
  14. if ! [ -x "$SCOUR" ]; then
  15. echo "scour executable not found, please install" >&2
  16. exit 3
  17. fi
  18. set +e
  19. CHECK_DIR='../'
  20. if [[ -d "$1" ]]; then
  21. CHECK_DIR=$1
  22. fi
  23. function recursive_optimize_images() {
  24. cd "$1" || return
  25. DIR_NAME=${PWD##*/}
  26. if [[ "$DIR_NAME" == "node_modules" ]]; then
  27. return
  28. elif [[ "$DIR_NAME" == "tests" ]]; then
  29. return
  30. fi
  31. # Optimize all PNGs
  32. for png in *.png
  33. do
  34. [[ -e "$png" ]] || break
  35. $OPTIPNG -o6 -strip all "$png"
  36. done
  37. # Optimize all JPGs
  38. for jpg in *.jpg
  39. do
  40. [[ -e "$jpg" ]] || break
  41. $JPEGOPTIM --strip-all "$jpg"
  42. done
  43. # Optimize all SVGs
  44. for svg in *.svg
  45. do
  46. [[ -e "$svg" ]] || break
  47. mv $svg $svg.opttmp
  48. $SCOUR --create-groups \
  49. --enable-id-stripping \
  50. --enable-comment-stripping \
  51. --shorten-ids \
  52. --remove-metadata \
  53. --strip-xml-prolog \
  54. --no-line-breaks \
  55. -i $svg.opttmp \
  56. -o $svg
  57. rm $svg.opttmp
  58. done
  59. # Check all subfolders
  60. for dir in */
  61. do
  62. [[ -e "$dir" ]] || break
  63. if [[ -d "$dir" ]]; then
  64. recursive_optimize_images "$dir"
  65. cd ..
  66. fi
  67. done
  68. }
  69. recursive_optimize_images "$CHECK_DIR"