Last active
November 23, 2017 16:19
-
-
Save edmondscommerce/405f1e4a684c3b1d0fd75cd690709b01 to your computer and use it in GitHub Desktop.
Magento Image Optimisation Script
This file contains 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
#!/usr/bin/env bash | |
readonly DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"; | |
cd $DIR; | |
set -e | |
set -u | |
set -o pipefail | |
standardIFS="$IFS" | |
IFS=$'\n\t' | |
# To use this script you'll need to install: | |
# - jpegoptim | |
# - optipng | |
# | |
# As well as set the mediaDir and skinDir below. | |
function echoTopLevelMsg() | |
{ | |
echo "[ $(date +%Y.%m.%dT%H:%M:%S) ] ===== $1 ====="; | |
} | |
echoTopLevelMsg "Running optimisation script"; | |
function usage() | |
{ | |
echo " | |
$0 <period> | |
- period: number of minutes since the script last ran (defaults to all images) | |
"; | |
} | |
function checkDependency() | |
{ | |
local dependency=$1; | |
command -v ${dependency} >/dev/null 2>&1 || { | |
echo >&2 "Please install '${dependency}' and then rerun this script."; | |
exit 1; | |
} | |
} | |
function processImages() | |
{ | |
local baseDir="$1"; | |
local match="$2"; | |
local tool="$3"; | |
shift 3; | |
echo "Processing images using: baseDir=${baseDir} period=-${period} match=${match} tool=${tool} toolArgs=$@"; | |
# Used \; in place of + because jpegoptim isn't able to handle large numbers of files in one go. | |
local periodFilter="" | |
if [[ "${period}" != "0" ]] | |
then | |
find ${baseDir} -type f -mmin -${period} -iregex ${match} -exec ${tool} "$@" {} \; | |
else | |
find ${baseDir} -type f -iregex ${match} -exec ${tool} "$@" {} \; | |
fi | |
echo "Processing complete"; | |
} | |
function optimiseJpeg() | |
{ | |
local match='.*\.jpg\|.*\.jpeg'; | |
local tool='jpegoptim'; | |
checkDependency ${tool}; | |
processImages ${mediaDir} ${match} ${tool} --strip-all -o; | |
processImages ${skinDir} ${match} ${tool} --strip-all -o; | |
} | |
function optimisePng() | |
{ | |
local match='.*\.png'; | |
local tool='optipng'; | |
checkDependency ${tool}; | |
processImages ${mediaDir} ${match} ${tool} -o2 -strip all; | |
processImages ${skinDir} ${match} ${tool} -o2 -strip all; | |
} | |
#defaults to processing all | |
readonly period=${1:-0}; | |
readonly mediaDir="${DIR}/path/to/media"; | |
readonly skinDir="${DIR}/path/to/skin"; | |
if [ ! -d "${mediaDir}" ]; then | |
echo "${mediaDir} does not exist"; | |
exit 1; | |
fi | |
if [ ! -d "${skinDir}" ]; then | |
echo "${skinDir} does not exist"; | |
exit 1; | |
fi | |
echoTopLevelMsg "Optimising JPG's"; | |
optimiseJpeg; | |
echoTopLevelMsg "Optimising PNG's"; | |
optimisePng; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment