Convert mov to gif


While creating my previous post on how to add an input accessory view to the iOS keyboard, I wanted to include gifs to better illustrate certain steps. If a picture is worth a thousand words, a movie must be worth even more, right?

The problem was, I had never made a gif before, but knew it would be a straightforward process. I began searching how to convert a .mov file — the default output format of QuickTime's screen recording — to a gif. I found this post, which seemed to answer my question, but I liked JasonM23's solution in the comments. I have modified his solution slightly, and would love to share it with you!

Dependencies

Two dependencies are required: ffmpeg and imagemagick. Both can be installed with Homebrew.

$ brew install ffmpeg
$ brew install imagemagick

The script

After the dependencies are installed, copy and paste the following into Terminal.

movtogif(){
     ffmpeg -i "$1" -r 20 -f image2pipe -vcodec ppm - |
     convert -delay 5 -layers Optimize -loop 0 - "$2"
}

This creates a temporary alias, movtogif, that you can use. After the Terminal window is closed, the alias won't be available again.

To make movtogif a permanent alias, add a function named __movtogif to your ~/.bash_profile file and make an alias that references it. This is necessary because bash aliases cannot accept parameters directly (Stack Overflow).

$ cat ~/.bash_profile

...

function __movtogif {
    if [ -z $5 ]; then
        echo -e "Invalid arguments.\n\tUsage: movtogif [input] [output] [frame rate] [delay] [scale]";
        return;
    fi

    ffmpeg -i $1 -vf scale=$5 -r $3 -f image2pipe -vcodec ppm - |
        convert -delay $4 -layers Optimize -loop 0 - $2
}

alias movtogif=__movtogif

Here's a one-liner to append the above to .bash_profile:

$ echo -e "function __movtogif {\n\tif [ -z \$5 ]; then\n\t\techo -e \"Invalid arguments.\\\n\\\tUsage: movtogif [input] [output] [frame rate] [delay] [scale]\";\n\t\treturn;\n\tfi\n\n\tffmpeg -i \"\$1\" -vf scale=\"\$5\" -r \"\$3\" -f image2pipe -vcodec ppm - |\n\tconvert -delay \"\$4\" -layers Optimize -loop 0 - \"\$2\"\n}\n\nalias movtogif=__movtogif" >> ~/.bash_profile

Then source your profile so the new functions are available:

$ source ~/.bash_profile

Usage

$ movtogif [input] [output] [frame rate] [delay] [scale]

Parameters