Skip to main content

Shortcut for ImageOptim.app tool, Lossless image optimizer for MacOS.

#!/usr/bin/env bash
set -e

# Shortcut for ImageOptim.app tool, Lossless image optimizer for MacOS.
# Only files and directories are allowed as arguments.
# Example:
#   imageoptim /path/to/image.png
#   imageoptim /path/to/images
#
# See: https://imageoptim.com/command-line.html
#
# Author: Jon LaBelle
# License: MIT
# Date: 2026-02-23
# https://jonlabelle.com/snippets/view/shell/imageoptimapp-cli-shortcut

# Check if ImageOptim.app is installed
if ! [[ -d "/Applications/ImageOptim.app" ]]; then
  echo "ImageOptim.app is not installed."
  echo "Download it from: https://imageoptim.com/mac"
  echo "After installation, run this command again."
  exit 1
fi

# Show help if no arguments are provided or if --help/-h is passed
if [[ "$#" -eq 0 ]] || [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
  cat << 'EOF'
ImageOptim - Lossless image optimizer for macOS

Usage:
  imageoptim <file|directory> [<file|directory> ...]
  imageoptim -h, --help              Show this help message

Arguments:
  file|directory                     Image file or directory containing images to optimize

Examples:
  imageoptim photo.jpg
  imageoptim ~/Pictures
  imageoptim image1.png image2.jpg ~/Desktop/images

Dependencies:
  ImageOptim.app                     https://imageoptim.com/mac
EOF
  exit 0
fi

# Validate that all provided files and directories exist
for arg in "$@"; do
  if ! [[ -e "$arg" ]]; then
    echo "Error: '$arg' does not exist"
    exit 1
  fi
done

# Run ImageOptim with error handling
/Applications/ImageOptim.app/Contents/MacOS/ImageOptim "$@" || {
  echo "ImageOptim failed. Check that your files are valid images."
  exit 1
}