Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Bulk Image Processing] Shell script that saves original, resizes, and compresses images.
#!/bin/sh
# Go to the root of images folder
# Run for each type of image, for example, PNG:
# $ find . -type f -name '*.png' -exec ~/path/to/script/bulk-image-processing.sh {} \; 2>&1 | tee log-png.txt;
file="${1}"
basename=${file%.*}
extension="${file##*.}"
copiedFile="$basename"_"ORIGINAL.$extension"
#using sips to retrieve the width
width=($(sips -g pixelWidth "${1}" | grep pixelWidth | grep -Eo "\d+"))
#Get file size
bytes=$(stat -f%z "${1}")
extension="${1##*.}"
#the width limit you want
widthLimit=2500
#500 kb
byteLimit=512000
minByteLimit=102400
#quality
minQuality=65
maxQuality=85
#Print out filesize
echo ${file}
if [[ $bytes -lt 1024 ]]; then
echo "Filesize: ${bytes}B"
elif [[ $bytes -lt 1048576 ]]; then
echo "Filesize: $(( (bytes + 1023)/1024 ))KiB"
else
echo "Filesize: $(( (bytes + 1048575)/1048576 ))MiB"
fi
#Print out width
echo "Width: ${width[0]}px"
# Copy file before resizing/compressing. Skip files less than 100kb.
if [[ $bytes -gt $minByteLimit ]]; then
cp "${file}" "${copiedFile}"
echo "COPY SUCCESS - copied original, created ${copiedFile}"
# Resize large images based on width
if [[ ${width[0]} -gt $widthLimit && $bytes -gt $byteLimit ]]; then
if [[ $bytes -gt $byteLimit ]]; then
sips -Z $widthLimit "${1}"
echo "RESIZE SUCCESS - Resized from ${width[0]}px to ${widthLimit}px wide."
else
echo "Resize Skipped - Did not resize dimensions, filesize OK."
fi
else
echo "Resize Skipped - Did not resize dimensions, within limits."
fi
echo "Compressing image to ${maxQuality}%..."
# Compress images based on type
if [ "$extension" == "png" ]; then
pngquant --quality=${minQuality}-${maxQuality}% --skip-if-larger "${1}" --output "${1}" --force
elif [ "$extension" == "jpg" ]; then
mogrify -strip -interlace Plane -quality ${maxQuality}% "${1}"
fi
if [ $? -eq 0 ]; then
echo "COMPRESSION SUCCESS"
fi
else
echo "Compression Skipped - file under 100kb"
fi
echo " --- "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment