Skip to content

Instantly share code, notes, and snippets.

@zmdominguez
Last active April 8, 2020 20:37
Show Gist options
  • Save zmdominguez/52d67cb67bbc5e90ff251a8913f515bf to your computer and use it in GitHub Desktop.
Save zmdominguez/52d67cb67bbc5e90ff251a8913f515bf to your computer and use it in GitHub Desktop.
Converts a .mov to an animated .gif.Requires ffmpeg and gifsicle.

mov_to_gif.sh

I have been asked quite a few times what I use to make animated gifs in my blog posts and tweets. I have been asked so much that I made it into a pinned post in my G+ profile. And now I got tired of copy-pasting all those commands so I made a script.

Usage

The script accepts two parameters:
-f - Required, the input file to be converted
-o - Optional, path and file where the output will be dumped. If not provided, the output will be named the same as the input, but with a .gif extension

Caveats

Script uses sips, ffmpeg (brew install ffmpeg), and gifsicle (brew install gifsicle). I am no master, in fact, I Googled for each command in this script. So use this at your own risk.

Attribution

Actual commands inspired by this post. Thanks to @gservat for helping when I was stuck.

#!/bin/bash
for i in "$@"
do
case $i in
-f=*|--file=*)
FILENAME="${i#*=}"
;;
-o=*|--out=*)
OUTPUT="${i#*=}"
;;
*)
# unknown option
;;
esac
done
# Check we have the required programs to run
for prog in ffmpeg gifsicle sips
do
type ${prog} >/dev/null 2>&1 || { echo >&2 "ERROR: ${prog} not found"; exit 1; }
done
if [ ! -f "$FILENAME" ]; then
echo "==================================="
echo " ERROR"
echo " Input file not found"
echo "==================================="
exit 1;
fi
if [ -z ${OUTPUT+x} ]; then
echo "==================================="
echo " WARNING"
echo " No output name detected, re-using"
echo " input filename."
echo "==================================="
OUTPUT=$(basename $FILENAME | cut -d '.' -f 1)
fi
delete_folder() {
rm -rf "$1"
}
PNGS_DIR=pngs
if [ -d "$PNGS_DIR" ]; then
delete_folder $PNGS_DIR
fi
# Create PNGs
mkdir pngs
echo "==================================="
echo " Creating PNGs"
echo "==================================="
ffmpeg -i $FILENAME -r 10 pngs/out%04d.png
GIFS_DIR=gifs
if [ -d "$GIFS_DIR" ]; then
delete_folder GIFS_DIR
fi
mkdir gifs
echo "==================================="
echo " Converting PNGs to GIFs"
echo "==================================="
sips -s format gif pngs/*.png --out gifs
# Convert into animated GIF
cd gifs/
echo "==================================="
echo " Making animated GIF\n"
gifsicle *.gif -w --optimize=3 --delay=3 --loopcount > ../$OUTPUT.gif
# Cleanup
cd ..
delete_folder $PNGS_DIR
delete_folder $GIFS_DIR
echo " DONE"
echo " File saved as \"$OUTPUT.gif\""
echo "==================================="
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment