Skip to content

Instantly share code, notes, and snippets.

@kenchopa
Last active May 18, 2024 12:28
Show Gist options
  • Save kenchopa/fa639a88f9453dc624ab065da9f9fc9e to your computer and use it in GitHub Desktop.
Save kenchopa/fa639a88f9453dc624ab065da9f9fc9e to your computer and use it in GitHub Desktop.
optimize images
#!/bin/bash
# Check if the required arguments were provided
if [ $# -lt 2 ]; then
echo "Usage: $0 resize_percentage compression_quality"
echo "Example: $0 50 75"
exit 1
fi
RESIZE_PERCENT=$1
COMPRESSION_QUALITY=$2
echo "Starting image optimization with $RESIZE_PERCENT% resize and $COMPRESSION_QUALITY% compression quality."
# Function to process a single image
process_image() {
local img=$1
local dir=$(dirname "$img")
local optimized_folder="$dir/optimized"
local base_name=$(basename "$img")
# Check and create an 'optimized' folder if it doesn't exist
if [ ! -d "$optimized_folder" ]; then
echo "Creating optimized folder in $dir"
mkdir -p "$optimized_folder"
fi
# Convert HEIC to JPG if necessary
if [[ "$img" == *.heic ]] || [[ "$img" == *.HEIC ]]; then
echo "Converting $img to JPG..."
local jpg_img="${img%.*}.jpg"
convert "$img" "$jpg_img"
img="$jpg_img"
base_name=$(basename "$img")
fi
# Resize and compress the image
echo "Processing $img..."
convert "$img" -auto-orient -resize "$RESIZE_PERCENT%" -quality "$COMPRESSION_QUALITY%" "$optimized_folder/$base_name"
echo "Saved optimized image as $optimized_folder/$base_name"
}
export -f process_image
export RESIZE_PERCENT
export COMPRESSION_QUALITY
# Recursively find images and process them
find . -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.heic" -o -iname "*.HEIC" \) -exec bash -c 'process_image "$0"' {} \;
echo "Image optimization complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment