Mary Knize

Creating an Animated GIF on the Command Line

1 min read

Art

I've been going through some pictures and video lately and found some video that I wanted to turn into an animated GIF. This project uses FFmpeg to extract frames from the video and ImageMagick to resize the frames and stitch them into an animated GIF.

I didn't have FFmpeg on my computer yet, so I quickly installed that.

sudo apt-get install ffmpeg

Next, I need to create a new directory for my image frames.

mkdir frames

This is the command that will create individual frames from the video. The -r option will specify the framerate. In this case I'm using 10 frames per second. Lower values will result in a choppier GIF with a smaller file size.

I'm naming the images sequentially. %03d will create sequential 3-digit numbers with leading zeroes.

ffmpeg -i pirates_caribbean.mp4 -r 10 'frames/frame-%03d.jpg'

The dimensions of the video are very large, and I want to make sure I get the filesize as small as possible. This command will use ImageMagick to resize every frame in the directory to 25% of the original size, as well as reduce the quality of the image by 50%. The video was already somewhat grainy from the low light conditions, so I'm not too upset at reducing the quality a bit further.

mogrify -resize 25% -quality 50% *.jpg

Finally, this last command uses ImageMagick to create an animated GIF with the name pirates.gif with a framerate of 10 frames per second that loops forever with the option -loop 0.

convert -delay 10 -loop 0 *.jpg pirates.gif

After these steps, I have my animated gif! I'm wondering if I could optimize it further since 26.6MB is still quite a hefty file size. Still, I'm pleased with the results, and I'm looking forward to making more GIFs with this technique.

Canonical URL