Skip to content

Instantly share code, notes, and snippets.

@hoajb
Created May 28, 2024 08:52
Show Gist options
  • Save hoajb/6fcabeda62a3f88c09a10f8d67985998 to your computer and use it in GitHub Desktop.
Save hoajb/6fcabeda62a3f88c09a10f8d67985998 to your computer and use it in GitHub Desktop.
Compress Images in folder in MacOs
#!/bin/bash
# Define the quality for compression
quality=80
# Create the result directory if it doesn't exist
mkdir -p result
# Find all images in the current directory (you can change the path as needed)
find . -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) | while read -r file; do
# Get the base name of the file (without path)
base_name=$(basename "$file")
# Create a new filename with "_compressed" appended before the file extension
new_file="result/${base_name%.*}_compressed.${base_name##*.}"
# Get the original file size in bytes
original_size=$(stat -f%z "$file")
# Use sips to compress the image
sips -s formatOptions $quality "$file" --out "$new_file"
# Get the compressed file size in bytes
compressed_size=$(stat -f%z "$new_file")
# Calculate the reduction percentage
reduction_percentage=$(echo "scale=2; 100 - ($compressed_size / $original_size * 100)" | bc)
# Print the reduction percentage
echo "Compressed $file -> $new_file (Reduction: $reduction_percentage%)"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment