Created
September 30, 2025 20:23
-
-
Save brockar/08e9956f616a40488e1894a7a8de2d74 to your computer and use it in GitHub Desktop.
compress_images_linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| set -euo pipefail | |
| usage() { | |
| echo "Usage: $0 [root_directory]" >&2 | |
| exit 1 | |
| } | |
| command -v magick >/dev/null 2>&1 || { | |
| echo "magick (ImageMagick) is required." >&2 | |
| exit 1 | |
| } | |
| ROOT="${1:-.}" | |
| [[ -d "$ROOT" ]] || usage | |
| TMP_DIR="$(mktemp -d)" | |
| cleanup() { rm -rf "$TMP_DIR"; } | |
| trap cleanup EXIT | |
| find "$ROOT" -type f \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.webp' \) -print0 | | |
| while IFS= read -r -d '' file; do | |
| ext="${file##*.}" | |
| tmp_file="$TMP_DIR/compress.$$.$ext" | |
| if magick "$file" -strip -quality 80 "$tmp_file"; then | |
| original_size=$(stat -c %s "$file") | |
| compressed_size=$(stat -c %s "$tmp_file") | |
| if ((compressed_size < original_size)); then | |
| mv "$tmp_file" "$file" | |
| echo "Compressed: $file (${original_size} -> ${compressed_size} bytes)" | |
| else | |
| rm -f "$tmp_file" | |
| echo "Skipped (no gain): $file" | |
| fi | |
| else | |
| rm -f "$tmp_file" | |
| echo "Compression failed: $file" >&2 | |
| fi | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment