Skip to content

Instantly share code, notes, and snippets.

@kuwabarahiroshi
Last active March 14, 2019 04:55
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 kuwabarahiroshi/94e3579a179af31fc816a290573ec5e3 to your computer and use it in GitHub Desktop.
Save kuwabarahiroshi/94e3579a179af31fc816a290573ec5e3 to your computer and use it in GitHub Desktop.
Convert videos (.mov, .mp4, etc.) to animated GIF via command line. (on Mac)
#!/bin/bash
# install ffmpeg and gifsicle if not exists
which ffmpeg > /dev/null || brew install ffmpeg
which gifsicle > /dev/null || brew install gifsicle
usage () {
echo "Usage:" 1>&2
echo " mov2gif [-d delay] [-o 1|2|3] [-r frame_rate] [-w width] input_file" 1>&2
echo "" 1>&2
echo "Example:" 1>&2
echo " mov2gif -w 640 -r 24 ~/Desktop/example.mov" 1>&2
echo "" 1>&2
echo "Options:" 1>&2
echo " -d delay Set the delay between frames to time in hundredths of a second." 1>&2
echo " -o level Optimize output GIF animations for space. Level determines how much optimization is done; higher levels take longer, but may have better results." 1>&2
echo " -r rate Set frame rate." 1>&2
echo " -w width Set width of output GIF." 1>&2
exit 1
}
while getopts "d:o:r:w:h" opt
do
case $opt in
d) DELAY=$OPTARG ;;
o) OPTIMIZE=$OPTARG ;;
r) RATE=$OPTARG ;;
w) WIDTH=$OPTARG ;;
h) usage ;;
esac
done
shift $((OPTIND - 1))
FILE=$1
if [ -z "$DELAY" ]; then
DELAY=3
fi
if [ -z "$OPTIMIZE" ]; then
OPTIMIZE=3
fi
if [ -z "$RATE" ]; then
RATE=24
fi
if [ -z "$WIDTH" ]; then
WIDTH=640
fi
if [ -z "$FILE" ]; then
echo "Please specify input file path." 1>&2
echo "" 1>&2
usage
fi
# Split frames into gifs with `ffmpeg` and then combine them into an animated gif with `gifsicle`
ffmpeg -i "$FILE" -vf scale=$WIDTH:-1 -r $RATE -f gif - | gifsicle --optimize=$OPTIMIZE --delay=$DELAY -o "$FILE.gif"
echo "" 1>&2
echo "generated $(cd $(dirname "$FILE.gif"); pwd)/$(basename "$FILE.gif")" 1>&2
# I like to check generated gif in a browser (with Chrome)
open -a 'Google Chrome.app' "$FILE.gif"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment