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
input— the name of the file to convert (with the.movextension)output— the name of the gif (with the.gifextension)frame rate(suggested: 20) — the gif's frame rate in fpsdelay(suggested: 5) — the delay between framesscale(suggested: original scale;iw*ih) — the size of the gif. Can be:- A specific width and height (e.g.
320:240) - A specific width, keeping aspect ratio (e.g.
20:-1) - A specific height, keeping aspect ratio (e.g.
-1:240) - Width/height using the
iw/ihconstants (e.g.iw*2:ih)
- A specific width and height (e.g.