From ba336aaf14e06f45029bb4fb5ba2ea7c0b49f626 Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Wed, 25 Mar 2026 15:07:08 +0100 Subject: [PATCH] update: image compress support size units --- README.md | 3 ++- image_compress.sh | 31 ++++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bcc01dc..add393a 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,9 @@ kill every wine process including processes hanging convert animated .webp at $1 (path) to a gif ### image_compress.sh -Usage: `./image_compress.sh ` +Usage: `./image_compress.sh ` Compress an image until it's below a specified target size. Output format is JPEG, regardless of the input format. +The target size can be without unit (default to bytes). Or in B, KB or MB, for bytes, kilo bytes and mega bytes (not case sensitive). (requires ImageMagick) ### convert_md_to_pdf.sh diff --git a/image_compress.sh b/image_compress.sh index 938242d..786fa26 100755 --- a/image_compress.sh +++ b/image_compress.sh @@ -2,13 +2,38 @@ input="$1" output="$2" -target_size=$3 +target_size_raw="$3" -if [[ -z "$input" || -z "$output" || -z "$target_size" ]]; then - echo "Usage: $0 input output.jpg " +if [[ -z "$input" || -z "$output" || -z "$target_size_raw" ]]; then + echo "Usage: $0 input output.jpg " exit 1 fi +parse_size() { + local size="$1" + + size=$(echo "$size" | tr '[:lower:]' '[:upper:]' | tr -d ' ') + + if [[ "$size" =~ ^([0-9]+(\.[0-9]+)?)(B|KB|MB)?$ ]]; then + value="${BASH_REMATCH[1]}" + unit="${BASH_REMATCH[3]}" + + case "$unit" in + ""|"B") multiplier=1 ;; + "KB") multiplier=1024 ;; + "MB") multiplier=$((1024 * 1024)) ;; + *) echo "Invalid size unit: $unit"; exit 1 ;; + esac + + awk "BEGIN {printf \"%d\", $value * $multiplier}" + else + echo "Invalid size format: $size" + exit 1 + fi +} + +target_size=$(parse_size "$target_size_raw") + compress_and_get_size() { local q=$1 magick "$work" -strip -interlace Plane -quality "$q" "$output"