Skip to content

Instantly share code, notes, and snippets.

@jroehl
Last active October 16, 2017 08:36
Show Gist options
  • Save jroehl/a3860a99518e631b39f54a0cdd287aa2 to your computer and use it in GitHub Desktop.
Save jroehl/a3860a99518e631b39f54a0cdd287aa2 to your computer and use it in GitHub Desktop.
Small helper script to resize and guetzlify jpgs via command line
#!/bin/bash
PROGNAME=$0
usage() {
cat << EOF >&2
Usage: $PROGNAME [-q <quality>] [-s <scale_shortest_side>] [-s <scale_largest_side>]
-q <quality>: quality of guetzli process | default [85]
-l <scale>: the scale of the largest side of the image
-s <scale>: the scale of the shortest side of the image
EOF
exit 1
}
#
# Minify images using the guetzli algorithm
# https://github.com/google/guetzli
# It can be very slow.
# Dont use it in a CI process.
#
guetzlify(){
echo "guetzlying $1"
guetzli --quality $2 "$1" "$1"
}
prepare_guetzlify(){
if [ -d "$1" ]; then
# is directory
find "$1" -type f -name "*.jpg" -print0 | while IFS= read -r -d '' file;
do
guetzlify "$file" "$2"
done
elif [[ -f "$1" ]] && [[ $1 == *.jpg || $1 == *.jpeg ]]; then
guetzlify "$1" "$2"
else
echo "$1 not found"
fi
}
#
# Resize images using imagemagick
#
resize() {
echo "resizing $1"
cmd="x$2>"
# check the aspect ratio
[ $(identify -format $check "$1") -eq 1 ] && cmd="$2x>"
convert "$1" -resize $cmd "$1"
}
prepare_resize(){
if [ ! -z $2 ]; then
check="%[fx:w<h?0:1]"
scale=$2
elif [ ! -z $3 ]; then
check="%[fx:w>h?0:1]"
scale=$3
else
return
fi
if [ -d "$1" ]; then
# is directory
find "$1" -type f -name "*.jpg" -print0 | while IFS= read -r -d '' file;
do
resize "$file" "$scale"
done
elif [[ -f "$1" ]] && [[ $1 == *.jpg || $1 == *.jpeg ]]; then
resize "$1" "$scale"
else
echo "$1 not found"
fi
}
quality=85
while getopts q:s:l: o; do
case $o in
(q) quality=$OPTARG;;
(l) scaleLargest=$OPTARG;;
(s) scaleShortest=$OPTARG;;
(*) usage
esac
done
shift "$((OPTIND - 1))"
path=$1
if which guetzli >/dev/null && which convert >/dev/null; then
for arg in "$@" ; do
prepare_resize "$arg" "$scaleLargest" "$scaleShortest"
prepare_guetzlify "$arg" $quality
done
else
brew update
brew install guetzli imagemagick
for arg in "$@" ; do
prepare_resize "$arg" "$scaleLargest" "$scaleShortest"
prepare_guetzlify "$arg" $quality
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment