Creating GIFs Using ffmpeg
ffmpeg is a fantastic tool for converting videos between various formats. I recently needed to create a GIF from a screen recording, which you can do with ffmpeg, but the command isn’t the easiest to remember.
/usr/local/bin/gif
#!/bin/bash
ffmpeg -i "$1" \
-vf "fps=10,scale=1080:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" \
-loop 0 "${2:-${i%.*}.gif}"
If you’re curious what this command does, here’s an explanation of each part, courtesy of ChatGPT.
-i "$1"
: Input file is the first command line argument.-vf
: Applies video filters.fps=10
: Sets the frames per second to 10.scale=1080:-1
: Scales the video to a width of 1080 pixels; height is set automatically to keep aspect ratio.flags=lanczos
: Uses the Lanczos filter for scaling, known for high quality.split[s0][s1]
: Splits the video stream into two streams,s0
ands1
.[s0]palettegen[p]
: Generates an optimized palette (p
) for the GIF from streams0
.[s1][p]paletteuse
: Applies the generated palette to streams1
.
-loop 0
: Makes the GIF loop indefinitely."${2:-${i%.*}.gif}"
: Output file is either the second command line argument, or the input file renamed to.gif
.
We can now call our gif
command like this to convert our video to a GIF!
gif input.mp4 output.gif