Skip to content

Instantly share code, notes, and snippets.

@parthnvaswani
Last active April 22, 2024 20:28
Show Gist options
  • Save parthnvaswani/b056db849eee6bf285365b3713447c33 to your computer and use it in GitHub Desktop.
Save parthnvaswani/b056db849eee6bf285365b3713447c33 to your computer and use it in GitHub Desktop.
# Example usage: sh compress_images.sh -i=images -o=compressed_images -w=1280 -e=jpg -f=webp
# Set default values
width="1280"
src="./images"
dest="./compressed_images"
extension="jpg"
output_format="webp"
function print_help {
echo "Usage: sh compress_images.sh -i=images -o=compressed_images -r=1280 -e=jpg -f=webp"
echo "Options:"
echo "-i, --input= Source directory (default: images)"
echo "-o, --output= Destination directory (default: compressed_images)"
echo "-r, --resolution= Resolution (default: 1280)"
echo "-e, --extension= Extension (default: jpg)"
echo "-f, --format= Output format (default: webp)"
echo "-h, --help Display help"
}
# Take inupt from user
for i in "$@"; do
case $i in
-i=* | --input=*)
src="${i#*=}"
shift
;;
-o=* | --output=*)
dest="${i#*=}"
shift
;;
-w=* | --width=*)
width="${i#*=}"
shift
;;
-e=* | --extension=*)
extension="${i#*=}"
shift
;;
-f=* | --format=*)
output_format="${i#*=}"
shift
;;
-h | --help)
print_help # Display help
exit 0
;;
*)
print_help # Display help
exit 1
;;
esac
done
# Throw error if source directory doesn't exist
if [ ! -d "$src" ]; then
echo "Source directory doesn't exist"
exit 1
fi
# Create destination directory if it doesn't exist
if [ ! -d "$dest" ]; then
mkdir $dest
fi
if [ "$output_format" == "webp" ]; then
mogrify -format webp -quality 82 -path $dest/ $dest/*.$extension
exit 0
fi
if [ "$output_format" == "jpg" ]; then
# This is taken from https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/
mogrify -path $dest/ -filter Triangle -define filter:support=2 -thumbnail $width -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB $src/*.$extension
exit 0
fi
echo "Invalid output format"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment