Skip to content

Instantly share code, notes, and snippets.

@k-miyata
Last active August 8, 2023 00:45
Show Gist options
  • Save k-miyata/bbf2ef7671066d48172f056fca9e1941 to your computer and use it in GitHub Desktop.
Save k-miyata/bbf2ef7671066d48172f056fca9e1941 to your computer and use it in GitHub Desktop.
Generate optimized GIFs with FFmpeg
#!/bin/bash
# GIF parameters
fps=24
width=960
if [ "$1" = "" ]; then
printf "\e[31mSpecify input files\e[m\n"
exit 1
fi
printf "GIF parameters:\n"
printf " - FPS: $fps\n"
printf " - Width: $width\n"
printf "\n"
readonly TMP_DIR=$(mktemp -d)
printf "Created temporary directory: $TMP_DIR\n"
printf "\n"
function cleanup {
rm -r $TMP_DIR && \
printf "Deleted temporary directory: $TMP_DIR\n"
}
trap cleanup EXIT
function generate {
local readonly PALETTE_FILE=$TMP_DIR/$(basename "$1").palette.png
local readonly OUTPUT_FILE=$1.gif
printf "Input $2/$3: $1\n" && \
printf "Generating palette...\n" && \
ffmpeg -v warning -y -i "$1" -vf "palettegen" "$PALETTE_FILE" && \
printf "Generated palette: $PALETTE_FILE\n" && \
printf "Generating GIF...\n" && \
ffmpeg -v warning -y -i "$1" -i "$PALETTE_FILE" -lavfi "fps=$fps,scale=$width:-1:flags=lanczos [x]; [x][1:v] paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle" "$OUTPUT_FILE" && \
printf "\e[32mGenerated GIF: $OUTPUT_FILE\e[m\n"
printf "\n"
}
index=1
for i in "$@"; do
generate "$i" $index $#
let index++
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment