|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# Bulk Image Compression Script |
| 4 | +# Requirements: imagemagick installed (IMv7 or later) |
| 5 | + |
| 6 | +# Set the source directory containing the images |
| 7 | +SOURCE_DIR="${1:-.}" # Default to current directory if no argument is passed |
| 8 | + |
| 9 | +# Create the destination directory by appending '-compressed' to the source directory name |
| 10 | +DEST_DIR="${SOURCE_DIR%/}-compressed" # Remove trailing slash from SOURCE_DIR, if any, before appending |
| 11 | + |
| 12 | +# Create the destination directory if it doesn't exist |
| 13 | +mkdir -p "$DEST_DIR" |
| 14 | + |
| 15 | +# Compression quality (adjust as needed) |
| 16 | +QUALITY=60 |
| 17 | + |
| 18 | +echo "Starting compression in directory: $SOURCE_DIR" |
| 19 | +echo "Compressed images will be saved to: $DEST_DIR" |
| 20 | +echo "Compression quality set to: $QUALITY" |
| 21 | + |
| 22 | +# Process .jpg and .png images |
| 23 | +for img in "$SOURCE_DIR"/*.{jpg,jpeg,png}; do |
| 24 | + # Skip if no matching files are found |
| 25 | + [ -e "$img" ] || continue |
| 26 | + |
| 27 | + # Get the filename without the directory |
| 28 | + filename=$(basename "$img") |
| 29 | + compressed_img="$DEST_DIR/$filename" |
| 30 | + |
| 31 | + # Compress and save to the destination directory |
| 32 | + magick "$img" -quality $QUALITY "$compressed_img" |
| 33 | + |
| 34 | + # Compare file sizes |
| 35 | + original_size=$(stat -f%z "$img") |
| 36 | + compressed_size=$(stat -f%z "$compressed_img") |
| 37 | + if (( compressed_size < original_size )); then |
| 38 | + echo "Compressed: $filename (Reduced from $original_size bytes to $compressed_size bytes)" |
| 39 | + else |
| 40 | + echo "No significant compression achieved for: $filename" |
| 41 | + fi |
| 42 | +done |
| 43 | + |
| 44 | +echo "Image compression completed!" |
0 commit comments