blog-contributions/imagecompress.sh
2025-03-29 09:16:20 +01:00

43 lines
1.3 KiB
Bash
Executable file

#!/bin/bash
# Run before executing:
# sudo apt install webp parallel
# Script will compress all images in directory given in the first parameter.
# JPEGs are lossy compressed, PNGs are losslessly compressed
# $ ./imagecompress.sh # current directory
# $ ./imagecompress.sh opsec/ # specified directory
# Already compressed WebP image will be kept, it only cares about image/png and image/jpeg mime.
# Compression commands are run in parallel using all available cores but it can take some time at first.
# WARNING:
# cwebp by default removes all EXIF, XMP and ICC tags.
# Images rotated only through Exif tag can have wrong orientation after compression.
# However we shouldn't have too much Exif here anyways.
DIR="${1:-$(pwd)}"
calculate_size() {
du -sh --exclude='.git' "$1" | awk '{print $1}'
}
initial_size=$(calculate_size "$DIR")
echo "Updating JPEGs"
# Lossy compression for JPEGs
find "$DIR" -print0 | parallel -0 '
[[ $(file --mime-type -b "{}") == "image/jpeg" ]] &&
cwebp "{}" -q 65 -m 6 -o "{}"
'
echo "Updating PNGs"
# Lossless compression for PNGs
find "$DIR" -print0 | parallel -0 '
[[ $(file --mime-type -b "{}") == "image/png" ]] &&
cwebp "{}" -q 100 -m 6 -lossless -o "{}"
'
final_size=$(calculate_size "$DIR")
echo "Compressed $initial_size -> $final_size"