Skip to content

Instantly share code, notes, and snippets.

@mnyrop
Last active August 26, 2017 16:31
Show Gist options
  • Save mnyrop/96f62cee941b068046b4ba6a797b5da2 to your computer and use it in GitHub Desktop.
Save mnyrop/96f62cee941b068046b4ba6a797b5da2 to your computer and use it in GitHub Desktop.
#!/bin/bash
# TO USE:
# 1. install imagemagick
# 2. place this file in a directory full of .tif files to convert
# 3. in the terminal, navigate into the directory of images and run $ `bash sudan_photo_resizer.sh`
# NOTE:
# image filenames CANNOT include whitespace
# for best results, use snake_case naming with no capitalization.
# images must be in in .tif format
# vars:
LG_WIDTH=1080 # width for large jpgs (px)
SM_WIDTH=600 # width for small jpgs (px)
THUMB_WIDTH=250
THUMB_HEIGHT=175
RES=72 # web resolution (ppi)
# dirs:
TIF_DIR="original-tif" # directory where original .tifs will go
LG_DIR="jpg-lg" # directory where large jpgs will go
SM_DIR="jpg-sm" # directory where small jpgs will go
THUMB_DIR="jpg-thumb"
# error catching:
## check to see if imagemagick is installed
command -v convert >/dev/null 2>&1 || { echo >&2 "Looks like imagemagick is not properly installed. Exiting."; exit 1; }
## check for whitespace in names
INVALID_NAMES=false
function assertNoSpaces {
if [[ "$1" != "${1/ /}" ]]
then
echo "INVALID FILE: ${1} contains whitespace." >&2
INVALID_NAMES=true
fi
}
for TIF in *.tif; do
assertNoSpaces "${TIF}"
done
if ${INVALID_NAMES}
then
echo "Please rename invalid image files and update the spreasheet before rerunning the script. Exiting."
exit 1
fi
# set-up:
if [ ! -d "${TIF_DIR}" ];
then
mkdir ${TIF_DIR}
fi
if [ ! -d "${LG_DIR}" ];
then
mkdir ${LG_DIR}
fi
if [ ! -d "${SM_DIR}" ];
then
mkdir ${SM_DIR}
fi
if [ ! -d "${THUMB_DIR}" ];
then
mkdir ${THUMB_DIR}
fi
# image processing:
NUM=0
for TIF in *.tif; do
TIF_TEMP=$(basename ${TIF} .tif)-temp.tif
JPG_LG=$(basename ${TIF} .tif)-${LG_WIDTH}.jpg
JPG_SM=$(basename ${TIF} .tif)-${SM_WIDTH}.jpg
JPG_THUMB=$(basename ${TIF} .tif)-thumb.jpg
echo "Processing ${TIF}"
convert -quiet ${TIF} -resize ${LG_WIDTH} -density ${RES} ${TIF_TEMP}
convert -quiet ${TIF_TEMP} ${JPG_LG}
convert -quiet ${JPG_LG} -resize ${SM_WIDTH} ${JPG_SM}
convert -quiet ${JPG_LG} -resize "${THUMB_WIDTH}x${THUMB_HEIGHT}^" -gravity Center -crop ${THUMB_WIDTH}x${THUMB_HEIGHT}+0+0 +repage ${JPG_THUMB}
((NUM++))
mv ${TIF} ${TIF_DIR}
mv ${JPG_LG} ${LG_DIR}
mv ${JPG_SM} ${SM_DIR}
mv ${JPG_THUMB} ${THUMB_DIR}
rm ${TIF_TEMP}
done
echo "Successfully converted ${NUM} images."
echo "Original tifs can be found in /${TIF_DIR}."
echo "Large jpgs can be found in /${LG_DIR}."
echo "Small jpgs in /${SM_DIR}."
echo "Thumbnail jpgs in /${THUMB_DIR}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment