-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimagequant.sh
More file actions
73 lines (60 loc) · 1.96 KB
/
Copy pathimagequant.sh
File metadata and controls
73 lines (60 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env bash
# Optimize PNG files larger than 800 KiB without keeping larger results.
# Usage: imagequant.sh [ROOT]
# Requires pngquant, oxipng, GNU find/stat, and awk.
set -euo pipefail
ROOT="${1:-.}"
MIN_SIZE="+800k"
if [[ $# -gt 1 ]]; then
echo "Usage: $0 [ROOT]" >&2
exit 2
fi
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
echo "Usage: $0 [ROOT]"
echo "Optimize PNG files larger than 800 KiB below ROOT (default: current directory)."
exit 0
fi
if [[ ! -d "$ROOT" ]]; then
echo "Error: directory not found: $ROOT" >&2
exit 2
fi
if ! command -v pngquant >/dev/null 2>&1; then
echo "Error: pngquant is not installed" >&2
exit 1
fi
if ! command -v oxipng >/dev/null 2>&1; then
echo "Error: oxipng is not installed" >&2
exit 1
fi
find "$ROOT" -type f \( -iname "*.png" \) -size "$MIN_SIZE" -print0 |
while IFS= read -r -d '' file; do
echo
echo "File: $file"
before_size=$(stat -c%s "$file")
backup="${file}.bak"
cp -p "$file" "$backup"
# pngquant reduces the palette with minimal quality loss.
# --skip-if-larger avoids replacing the file with a larger result.
if pngquant --quality=90-100 --skip-if-larger --ext .png --force "$file"; then
:
else
echo "pngquant could not process the file; trying oxipng only"
cp -p "$backup" "$file"
fi
# oxipng performs lossless PNG optimization.
oxipng -o 4 --strip safe "$file" >/dev/null
after_size=$(stat -c%s "$file")
if [ "$after_size" -ge "$before_size" ]; then
cp -p "$backup" "$file"
rm -f "$backup"
echo "No size reduction; restored the original"
echo "Size: $before_size bytes"
else
rm -f "$backup"
saved=$((before_size - after_size))
percent=$(awk "BEGIN { printf \"%.2f\", ($saved / $before_size) * 100 }")
echo "Before: $before_size bytes"
echo "After: $after_size bytes"
echo "Saved: $saved bytes ($percent%)"
fi
done