#!/bin/bash # Batch convert all PNG/JPG/JPEG to WebP # Usage: ./convert_to_webp.sh # Output: appends .webp to each filename (e.g., "file.png" -> "file.png.webp") # This avoids filename collisions - you can clean up names later set -e echo "=== WebP Batch Conversion ===" echo "Starting at: $(date)" echo "" TOTAL_ORIGINAL=0 TOTAL_WEBP=0 CONVERTED=0 SKIPPED=0 # Function to format bytes format_bytes() { local bytes=$1 if (( bytes >= 1073741824 )); then echo "$(echo "scale=2; $bytes / 1073741824" | bc) GB" elif (( bytes >= 1048576 )); then echo "$(echo "scale=2; $bytes / 1048576" | bc) MB" elif (( bytes >= 1024 )); then echo "$(echo "scale=2; $bytes / 1024" | bc) KB" else echo "$bytes B" fi } echo "Processing PNG files (lossless)..." for f in *.png; do [ -f "$f" ] || continue original_size=$(stat -c%s "$f") TOTAL_ORIGINAL=$((TOTAL_ORIGINAL + original_size)) output="${f}.webp" # Skip if already converted if [ -f "$output" ]; then echo " SKIP (already exists): $f" SKIPPED=$((SKIPPED + 1)) continue fi echo -n " Converting: $f ... " cwebp -lossless "$f" -o "$output" > /dev/null 2>&1 if [ -f "$output" ] && [ -s "$output" ]; then webp_size=$(stat -c%s "$output") TOTAL_WEBP=$((TOTAL_WEBP + webp_size)) savings=$((original_size - webp_size)) pct=$(echo "scale=1; $savings * 100 / $original_size" | bc) echo "DONE [$(format_bytes $original_size) -> $(format_bytes $webp_size) | ${pct}% saved]" CONVERTED=$((CONVERTED + 1)) else echo "FAILED" fi done echo "" echo "Processing JPG/JPEG files (quality 100)..." for f in *.jpg *.jpeg; do [ -f "$f" ] || continue original_size=$(stat -c%s "$f") TOTAL_ORIGINAL=$((TOTAL_ORIGINAL + original_size)) output="${f}.webp" # Skip if already converted if [ -f "$output" ]; then echo " SKIP (already exists): $f" SKIPPED=$((SKIPPED + 1)) continue fi echo -n " Converting: $f ... " cwebp -q 100 "$f" -o "$output" > /dev/null 2>&1 if [ -f "$output" ] && [ -s "$output" ]; then webp_size=$(stat -c%s "$output") TOTAL_WEBP=$((TOTAL_WEBP + webp_size)) savings=$((original_size - webp_size)) pct=$(echo "scale=1; $savings * 100 / $original_size" | bc) echo "DONE [$(format_bytes $original_size) -> $(format_bytes $webp_size) | ${pct}% saved]" CONVERTED=$((CONVERTED + 1)) else echo "FAILED" fi done echo "" echo "=== Summary ===" echo "Converted: $CONVERTED files" echo "Skipped: $SKIPPED files (already exist)" echo "" echo "Original total: $(format_bytes $TOTAL_ORIGINAL)" echo "WebP total: $(format_bytes $TOTAL_WEBP)" if [ $TOTAL_ORIGINAL -gt 0 ]; then SAVINGS=$((TOTAL_ORIGINAL - TOTAL_WEBP)) PCT=$(echo "scale=1; $SAVINGS * 100 / $TOTAL_ORIGINAL" | bc) echo "Space saved: $(format_bytes $SAVINGS) ($PCT%)" fi echo "" echo "Finished at: $(date)" echo "" echo "=== Git LFS Note ===" echo "The .webp files are NOT added to git." echo "To track them with Git LFS later, run:" echo " git lfs track '*.webp'" echo " git add .gitattributes" echo " git add *.webp" echo " git commit -m 'Add WebP versions'"