Skip to content

Instantly share code, notes, and snippets.

@patsma
Created April 24, 2025 05:09
Show Gist options
  • Save patsma/40807f0065486a6f7c6ea71f56a71c99 to your computer and use it in GitHub Desktop.
Save patsma/40807f0065486a6f7c6ea71f56a71c99 to your computer and use it in GitHub Desktop.
#!/bin/bash
# optimize-images: Universal image optimization script
# Usage: optimize-images [options] [input_path]
# If no input path is provided, uses current directory
# Options:
# -q, --quality JPEG/WebP quality (default: 82)
# -w, --width Maximum width (default: 1920, maintains aspect ratio)
# -f, --format Convert to format (jpg, png, webp)
# --help Show this help message
# Default values
QUALITY=82
FORMAT=""
MAX_WIDTH=1920
INPUT_PATH="."
# Check if required commands exist
command -v convert >/dev/null 2>&1 || { echo "Error: ImageMagick (convert) is required but not installed. Install it with: brew install imagemagick"; exit 1; }
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
-q|--quality)
QUALITY="$2"
shift 2
;;
-w|--width)
MAX_WIDTH="$2"
shift 2
;;
-f|--format)
FORMAT="$2"
shift 2
;;
--help)
echo "Usage: optimize-images [options] [input_path]"
echo "If no input path is provided, uses current directory"
echo "Options:"
echo " -q, --quality JPEG/WebP quality (default: 82)"
echo " -w, --width Maximum width (default: 1920, maintains aspect ratio)"
echo " -f, --format Convert to format (jpg, png, webp)"
echo " --help Show this help message"
exit 0
;;
*)
INPUT_PATH="$1"
shift
;;
esac
done
# Function to optimize a single image
optimize_image() {
local input="$1"
local original_size=$(stat -f %z "$input")
# Prepare conversion options
local convert_opts="-strip -interlace Plane -quality $QUALITY -resize ${MAX_WIDTH}x>"
# If format is specified, prepare new filename
local output="$input"
if [ ! -z "$FORMAT" ]; then
local dirname=$(dirname "$input")
local filename=$(basename "$input")
local name="${filename%.*}"
output="$dirname/${name}.${FORMAT}"
fi
# Convert and optimize
convert "$input" $convert_opts "$output"
# Get new file size
local new_size=$(stat -f %z "$output")
# Calculate reduction percentage
local reduction=$(echo "scale=2; (1 - $new_size/$original_size) * 100" | bc)
echo "Optimized: $input"
echo " Original size: $(echo "scale=2; $original_size/1024" | bc)KB"
echo " New size: $(echo "scale=2; $new_size/1024" | bc)KB"
echo " Reduction: ${reduction}%"
echo
}
# Process files recursively
find "$INPUT_PATH" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.webp" \) -print0 | while IFS= read -r -d '' file; do
optimize_image "$file"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment