Resizing a whole directory of images recursively on OSX

This is a quick script to resize all JPEGs in a folder recursively and output them to another folder. It will only resize new images on subsequent runs to save time. The settings in the example are to max width 1280px and file size 200KB.

  1. Install brew and dependencies:

    brew install imagemagick jpegoptim
  2. Download or copy and paste the following script resize-pics.sh:

    #!/bin/bash
    
    set -o nounset
    set -o errexit
    
    DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    
    cd "$DIR"
    
    export SOURCE_DIR="Pics"
    export TARGET_DIR="Pics Resized"
    
    mkdir -p "$TARGET_DIR"
    
    function resizeimage {
    
        IMAGE_PATH="${1#*/}"
        OUTPUT_PATH="${TARGET_DIR}/${IMAGE_PATH}"
    
        if [[ "$OUTPUT_PATH" =~ '/' ]]
        then
            mkdir -p "$(dirname "$OUTPUT_PATH")"
        fi
    
        if [ ! -e "${OUTPUT_PATH}" ]
        then
            echo "Resizing ${IMAGE_PATH}"
            convert -resize '1280x>' "${SOURCE_DIR}/${IMAGE_PATH}" "$OUTPUT_PATH"
            jpegoptim -S200 "$OUTPUT_PATH"
        fi
    }
    
    export -f resizeimage
    
    find "$SOURCE_DIR" -type f \( -iname '*.jpg' -o -iname '*.jpeg' \) -exec bash -c 'resizeimage "[email protected]"' bash {} \;
    
    read -rp "Done. Press Enter to exit"

  3. Customize SOURCE_DIR (default Pics) and TARGET_DIR (default Pics Resized) in the script.

  4. Make the script executable:

    chmod u+x resize-pics.sh
  5. Either run the script from Terminal as ./resize-pics.sh or set it up to be double-clickable in Finder (see https://stackoverflow.com/questions/5125907/how-to-run-a-shell-script-in-os-x-by-double-clicking)


comments powered by Disqus