Convert video to animated GIF on Linux (BASH)

GIFs went away for a while, but now seem to have seen a resurgence in popularity. This snippet details how to turn an arbitrary video snippet into an animated gif (though you may get quite a large filesize, depending on your input, see the optimisation guide to help reduce the size as needed).

Details

  • Language: BASH

Snippet

# Extract images from the video. 5 Frames per second (-r 5)
# see below if you want to adjust 5fps.
#
mkdir imgs
ffmpeg -i {input video} -r 5 'imgs/frame-%03d.jpg'

cd imgs

# If you want to reduce resolution, nows a good time to do it
# 
# for example
#
# for i in *.jpg; do convert $i -resize x400 -quality 75 $i; done

# Now turn the images into a gif using ImageMagick
#
# We use loop 0 so the gif is in an infinite loop.
convert -delay 20 -loop 0 *.jpg mygif.gif

# If you want more frames per second, use the following matrix to adjust the value of 'delay'
#
# 1   = 100fps
# 2   = 50fps
# 4   = 25fps
# 5   = 20fps
# 10  = 10fps
# 20  = 5fps
# 25  = 4fps
# 50  = 2fps
# 100 = 1fps
#
# e.g. for 50fps, we'd do
#
# ffmpeg -i {input video} -r 50 'imgs/frame-%03d.jpg'
# cd imgs
# convert -delay 2 -loop 0 *.jpg mygif.gif
#

Usage Example

mkdir imgs
ffmpeg -i rccar.mp4 -r 5 'imgs/frame-%03d.jpg'
cd imgs
for i in *.jpg; do convert $i -resize x300 -quality 75 $i; done
convert -delay 20 -loop 0 *.jpg rccar.gif

# Result - https://static1.bentasker.co.uk/images/Documentation/rc_car_gearbox_repair/rccar.gif