check-png-sizes.sh 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env bash
  2. set -eo pipefail
  3. # How many bytes optipng has to be able to strip out of the file for the optimization to be worth it. The default is 1 KiB.
  4. : "${MINIMUM_OPTIMIZATION_BYTES:=1024}"
  5. script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
  6. cd "${script_path}/.."
  7. if ! command -v optipng >/dev/null ; then
  8. echo 'optipng is not installed, skipping png size check.'
  9. echo 'Please install optipng for your system to run this check.'
  10. exit 0
  11. fi
  12. files=()
  13. for file in "$@"; do
  14. if [[ "${file}" == *".png" ]]; then
  15. files+=("${file}")
  16. fi
  17. done
  18. if (( ${#files[@]} )); then
  19. # We need to allow optipng to write output so we can check what it actually did. We use a dummy file that's discarded afterwards.
  20. optimizations=$( printf '%s\0' "${files[@]}" |\
  21. xargs -0 -n1 optipng -strip all -out dummy-optipng-output.png -clobber 2>&1 |\
  22. grep -i -e 'Output IDAT size =' |\
  23. sed -E 's/Output IDAT size = [0-9]+ byte(s?) \(([0-9]+) byte(s?) decrease\)/\2/g;s/Output IDAT size = [0-9]+ byte(s?) \(no change\)/0/g' |\
  24. awk "{ if (\$1 >= $MINIMUM_OPTIMIZATION_BYTES) { S+=\$1 } } END { print S }")
  25. rm -f dummy-optipng-output.png dummy-optipng-output.png.bak
  26. optimizations="${optimizations:-0}"
  27. if [[ "$optimizations" -ne 0 ]] ; then
  28. echo "There are non-optimized PNG images in Base/. It is possible to reduce file sizes by at least $optimizations byte(s)."
  29. # shellcheck disable=SC2016 # we're not trying to expand expressions here
  30. echo 'Please run optipng with `-strip all` on modified PNG images and try again.'
  31. exit 1
  32. fi
  33. else
  34. echo 'No PNG images to check.'
  35. fi