Skip to content

Instantly share code, notes, and snippets.

@audrenbdb
Created June 24, 2024 19:33
Show Gist options
  • Save audrenbdb/c1ce6aef03f10ff9d9cfc6aefc58b752 to your computer and use it in GitHub Desktop.
Save audrenbdb/c1ce6aef03f10ff9d9cfc6aefc58b752 to your computer and use it in GitHub Desktop.
Minify contents of images in a folder
#!/bin/bash
# Requirements (macos)
# brew install imagemagick
# brew install jpegoptim
# brew install optipng
# Check if both arguments are provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <source_folder> <destination_folder>"
exit 1
fi
# Set the input and output directories from arguments
input_dir="$1"
output_dir="$2"
# Check if the input directory exists
if [ ! -d "$input_dir" ]; then
echo "Error: Source folder '$input_dir' does not exist."
exit 1
fi
# Create the output directory if it doesn't exist
mkdir -p "$output_dir"
# Loop through all image files in the input directory
for file in "$input_dir"/*.{jpg,jpeg,png,gif,webp}; do
if [ -f "$file" ]; then
filename=$(basename "$file")
extension="${filename##*.}"
filename="${filename%.*}"
# Copy files with .webp in the name without altering them
if [[ "$filename" == *".webp"* || "$extension" == "webp" ]]; then
echo "Copying $filename without alteration as it contains .webp"
cp "$file" "$output_dir/"
continue
fi
# Resize and compress other image types
magick "$file" -resize 500x500^ -gravity center -extent 500x500 "$output_dir/${filename}.${extension}"
# Optimize JPEG images
if [[ "$extension" == "jpg" || "$extension" == "jpeg" ]]; then
jpegoptim --strip-all --max=85 "$output_dir/${filename}.${extension}"
fi
# Optimize PNG images
if [[ "$extension" == "png" ]]; then
optipng -o5 "$output_dir/${filename}.${extension}"
fi
echo "Processed: $filename"
fi
done
echo "Image processing complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment