Manipulating GIFs with ffmpeg

Convert video to GIF, including trimming to length

1. Convert video to image sequence

$ ffmpeg -ss 1:23 -i input.mp4 -frames:v 100 image-%03d.png
-ss 1:23
sets the start time
-frames:v 100
takes only 100 frames from the input
-t 2
takes only 2 seconds of video from the input (alternative to -frames:v)

2. Resize selected frames

After reviewing the images and deciding I want frames 7 through 19:

$ ffmpeg -start_number 7 -i image-%03d.png -frames:v 12 -vf scale=480:270 imagescaled-%03d.png
-start_number 7
starts at frame number 7 (output numbering will start from 1, so -start_number is no longer needed after this)
-frames:v 12
as above takes 12 frames from the input

3. Generate palette

If we don’t do this, ffmpeg will guess and screw up all the colors.

$ ffmpeg -i imagescaled-%03d.png -filter_complex "[0:v] palettegen" palette.png

4. Generate GIF from images using palette

$ ffmpeg -i imagescaled-%03d.png -i palette.png -filter_complex "[0:v][1:v] paletteuse" output.gif

Scale a gif while preserving palette

Generate palette, as above:

$ ffmpeg -i input.gif -filter_complex "[0:v] palettegen" palette.png

Scale and reapply palette: (ffmpeg gets confused and makes a 10MB gif if you only use scale)

$ ffmpeg -i input.gif -i palette.png -filter_complex "[0:v] scale=800:480:flags=neighbor [tmp]; [tmp][1:v] paletteuse" input_2x.gif