Skip to content

Instantly share code, notes, and snippets.

@statico
Last active January 11, 2023 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statico/204235dcdc326d038d8af16e48115cb0 to your computer and use it in GitHub Desktop.
Save statico/204235dcdc326d038d8af16e48115cb0 to your computer and use it in GitHub Desktop.
Use gifsicle to resize GIFs for Slack emoji
#!/usr/bin/env bash
set -eo pipefail
srcdir="$1"
if [ -z "$srcdir" ]; then
echo "usage: $0 <dir>"
exit 1
fi
destdir="$srcdir-slack"
mkdir -p "$destdir"
MAXSIZE=128000
sizeof() {
wc -c "$1" | perl -lane'print $F[0]'
}
numframes() {
gifsicle "$1" -I | grep -E "\d+ images" --only-matching | grep "[0-9][0-9]*" --only-matching
}
delayof() {
local x=$(gifsicle "$1" -I | grep -E 'delay \d+(?:\.\d+)' --only-matching | grep -E '\d.*' --only-matching | tail -n 1)
echo "$x * 100" | bc | grep -E '\d+' --only-matching | head -n 1
}
g="gifsicle -O3 --colors=256"
for src in "$srcdir"/*.gif; do
dest="$destdir/$(basename "$src")"
n="$(numframes "$src" || echo 0)"
d="$(delayof "$src" || echo 0)"
declare -a cmds=(
'$g --resize=128x128 \"$src\" -o \"$dest\"'
'$g --resize=96x96 \"$src\" -o \"$dest\"'
'$g --resize=64x64 \"$src\" -o \"$dest\"'
'$g --resize=128x128 --lossy=30 \"$src\" -o \"$dest\"'
'$g --resize=96x96 --lossy=30 \"$src\" -o \"$dest\"'
'$g --resize=64x64 --lossy=30 \"$src\" -o \"$dest\"'
'$g --resize=128x128 --lossy=80 \"$src\" -o \"$dest\"'
'$g --resize=96x96 --lossy=80 \"$src\" -o \"$dest\"'
'$g --resize=64x64 --lossy=80 \"$src\" -o \"$dest\"'
'$g --resize=128x128 \"$src\" -d $((d*2)) $(seq -f \"#%g\" 0 2 $(($n - 1))) -o \"$dest\" -o \"$dest\"'
'$g --resize=96x96 \"$src\" -d $((d*3)) $(seq -f \"#%g\" 0 3 $(($n - 1))) -o \"$dest\" -o \"$dest\"'
'$g --resize=64x64 \"$src\" -d $((d*3)) $(seq -f \"#%g\" 0 3 $(($n - 1))) -o \"$dest\" -o \"$dest\"'
'$g --resize=128x128 \"$src\" -d $((d*3)) $(seq -f \"#%g\" 0 3 $(($n - 1))) -o \"$dest\" -o \"$dest\"'
'$g --resize=96x96 \"$src\" -d $((d*3)) $(seq -f \"#%g\" 0 3 $(($n - 1))) -o \"$dest\" -o \"$dest\"'
'$g --resize=64x64 \"$src\" -d $((d*3)) $(seq -f \"#%g\" 0 3 $(($n - 1))) -o \"$dest\" -o \"$dest\"'
)
echo "$src"
for cmd in "${cmds[@]}"; do
rm -f "$dest"
echo "> $cmd"
eval eval $cmd
if [ $(sizeof "$dest") -le "$MAXSIZE" ]; then
break
fi
done
echo -n "Final size: $(sizeof "$dest")"
if [ $(sizeof "$dest") -gt "$MAXSIZE" ]; then
echo "********** STILL TOO BIG **********"
fi
echo
echo
done
@statico
Copy link
Author

statico commented Jan 11, 2023

Bulk deletion snipped in case you make a mistake: https://gist.github.com/nealey/5549ec14a182bc59510dd76f62e2bc64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment