Making animated gifs from command line Tue, Feb 26, 2013

Sometimes when you're watching your favorite show, a perfect moment comes along that you just gotta capture and share with everyone. That's where the animated gif comes in. Though they're really popular with the kids these days, they're surprisingly hard to make. Luckily there's some powerful open source command line tools that can help you: ffmpeg, ImageMagick and gifsicle. If you're on OS X and have Homebrew set up, all you have to do is run:

brew install ffmpeg imagemagick gifsicle

Boom. So the first thing you'll need is a video file. They're getting quite rare these days since everything's streaming now, but assuming you've got one, you'll wanna find the start time of the moment you wanna capture, and how long the moment is.

Once you've know those two things, you'll wanna fire up ffmpeg to extract the moment from the video into a series of gif images. For example, if I wanted 5 seconds from myvideo.avi, starting at 9 minutes and 52 seconds in, I'd run:

ffmpeg -ss 00:09:52 -t 5 -i /path/to/myvideo.avi myanim-%3d.gif

This will output a series of myanim-001.gif, myanim-002.gif, etc images to the current directory, with one image per frame in the video.

From here, you could just compile these images into an animated gif with gifsicle:

gifsicle --delay=4 --loop myanim-*.gif > myanim.gif

That will create an animated gif myanim.gif from all of the frames that ffmpeg extract with a delay of 4 hundreths of a second between each frame, looped forever. You can view it in a browser like Chrome this:

open -a /Applications/Google\ Chrome.app myanim.gif

Most of the time though, this will generate an image file that's way to large for you to post or others to view in a timely manner, so you'll wanna crop and scale down the image using ImageMagick, specifically ImageMagick's mogrify tool.

mogrify -crop 1024x1024+200+0 +repage -resize 480 myanim-*.gif

This will crop the images to 1024 by 1024 with a horizontal offset of 200 pixels, remove the cropped portion from the image, then resize it proportionally to 480 by 480. Now you can rerun the gifsicle command and you'll have a nice and svelte animated gif file on your hands!

Note that gifsicle has some options to crop and scale the animation, but I found that it doesn't preserve the quality of the images as well as mogrify does. Also be careful with mogrify because it modifies the image files you point it at, so you may want to make a copy of the first frame and test your mogrify command on it before applying the command to all the frames. Though if you mess up, you can always run ffmpeg again.

Enjoy!