Skip to content

Instantly share code, notes, and snippets.

@tancredi
Created November 10, 2020 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tancredi/cfeadb36f8688a95f0324009c82f6a98 to your computer and use it in GitHub Desktop.
Save tancredi/cfeadb36f8688a95f0324009c82f6a98 to your computer and use it in GitHub Desktop.
Recursive bash ImageMagick thumbnail generation tool
#!/bin/bash
declare -a EXTS=("jpg" "jpeg" "png" "gif")
DEBUG=0
WIDTH=100
HEIGHT=100
OUT_DIR=""
SUFFIX=""
INPUTS=()
usage() {
echo ""
echo "Usage: $0 <input> -o <out-dir> [ -w <width> -h <height> -s <suffix> -d ]"
echo ""
echo "Explanation: Recursively generates thumbnails with ImageMagick from a \
specified input path to an output directory, replicating the same relative tree."
echo ""
exit 2
}
run() {
parseOptions $@
validateOptions
debugOptions
generateThumbnails
}
relativePath() {
s=$(cd ${1%%/};pwd); d=$(cd $2;pwd); b=; while [ "${d#$s/}" == "${d}" ]
do s=$(dirname $s);b="../${b}"; done; echo ${b}${d#$s/}
}
debug() {
if [ $DEBUG == 1 ]
then
for value in "${@}"
do
echo -e $value
done
fi
}
debugOptions() {
debug "\n
+-----------------+\n
|++++ Options ++++|:\n
+-----------------+\n
\n
- Width: ${WIDTH}\n
- Height: $HEIGHT\n
- Inputs: ${INPUTS[*]}\n
- Output: ${OUT_DIR}\n
- Suffix: ${SUFFIX}\n
"
}
parseOptions() {
while [ $# -gt 0 ]
do
unset OPTIND
unset OPTARG
while getopts "w: h: o: s: d" options
do
case $options in
h)
if [ ! -z "$OPTARG" ]
then
HEIGHT=$OPTARG
else
usage
fi
;;
w)
WIDTH=$OPTARG
;;
o)
OUT_DIR=$OPTARG
;;
s)
SUFFIX=$OPTARG
;;
d)
DEBUG=1
;;
?)
usage
;;
esac
done
shift $((OPTIND-1))
INPUTS=(${INPUTS[@]} $1)
shift
done
}
validateOptions() {
if [ ${#INPUTS[@]} -eq 0 ]
then
echo "Please specify at least one input dir"
usage
fi
if [ -z $OUT_DIR ]
then
echo "Please specify an output directory with -o"
usage
fi
if [ ! -d $OUT_DIR ]
then
echo "Output directory \"${OUT_DIR}\" doesn't exist"
exit 1
fi
}
generateThumbnails() {
for input in "${INPUTS[@]}"
do
debug "Processing input: ${input}..."
if [ ! -d $input ]
then
echo "Output directory \"${input}\" doesn't exist"
exit 1
fi
for file in $(find $input -name '*.*')
do
ext="${file##*.}"
if [[ " ${EXTS[@]} " =~ " ${ext} " ]]; then
debug "Processing file: ${file}..."
relativePath=$(relativePath $input $(dirname $file))
outPath="${OUT_DIR}/${relativePath}"
thumbnailPath="${outPath}/$(basename $file ".${ext}")${SUFFIX}.${ext}"
mkdir -p $outPath
convert -thumbnail "${WIDTH}x${HEIGHT}^" -gravity center -extent "${WIDTH}x${HEIGHT}" $file $thumbnailPath
debug "Generated ${thumbnailPath}"
fi
done
done
debug "\nDone"
}
run $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment