Last active
August 30, 2017 16:01
-
-
Save joahking/09469634d2191bf5a5ebe77cad00d866 to your computer and use it in GitHub Desktop.
Script used in ifeelmaps.com to optimise images as suggested by PageSpeed Insights
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Convert images received as list of filenames over stdin | |
# | |
# Uses imagemagick's convert script https://www.imagemagick.org/script/convert.php | |
# Follows suggestions on https://developers.google.com/speed/docs/insights/OptimizeImages | |
# | |
# Usage: | |
# find . -path './*original*' -type f | sed 's/\.\///' | ./convert-imgs.sh 615 > converted_images | |
# | |
# Arguments: | |
# stdin - list of filenames | |
# width - number to resize image's width to. Optional | |
# | |
# NOTE: the filenames should not start with `./`, in general filenames should not have dots, only the one for the file extension | |
# since the script relies on finding the dot in filename to get the image extension and apply the correct conversion | |
# (thus the piping to `sed 's/\.\///'` above in Usage) | |
# | |
# e.g. a good list of images is: | |
# | |
# image1.png | |
# image2.png | |
# | |
# AND NOT (as it will break the script): | |
# ./image1.png | |
# ./image2.png | |
suffix=imagemagick_converted # the suffix used to generate converted images | |
# generate convert's arguments for images extensions | |
png_args="-strip" | |
jpg_args="-strip -sampling-factor 4:2:0 -quality 85 -interlace JPEG" | |
if [ -z $1 ] # was width passed? | |
then | |
# https://www.imagemagick.org/script/command-line-processing.php#geometry "Width given, height automagically selected to preserve aspect ratio." | |
png_args="$png_args -resize $1" | |
jpg_args="$jpg_args -resize $1" | |
fi | |
while read -r filename; # loop over filenames passed over stdin | |
do | |
echo $filename # print file processed | |
dot_index=`expr index $filename .` # find the index of dot in filename string | |
name=${filename:0:dot_index-1} # name = characters before the dot | |
extension=${filename:dot_index} # extension = characters after the dot | |
converted_img="$name"_"$suffix".$extension | |
case $extension in | |
*jpg|JPG|jpeg|JPEG*) | |
# TODO use Progressive JPG ? read http://itstillworks.com/progressive-jpeg-12211723.html pros and cons | |
`convert $filename $jpg_args $converted_img` | |
;; | |
*png|PNG|gif|GIF*) | |
`convert $filename $png_args $converted_img` | |
;; | |
*) ;; | |
esac | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment