1. Overview

In this tutorial, we’ll learn how to convert videos to gifs using the command-line FFmpeg tool.

FFmpeg is a free and open-source software project consisting of a suite of libraries and programs for handling video, audio, and other multimedia files and streams. In addition, the FFmpeg command-line tool helps us convert various audio and video formats.

2. Installing FFmpeg

There are many ways to install FFmpeg. Most importantly, we need to make sure we install the latest stable version of FFmpeg so we can use its newest features.

We can use snap to install the latest stable version of FFmpeg on a Debian/Ubuntu machine:

$ sudo snap install ffmpeg

Now we should check if it’s actually installed:

$ ffmpeg -version
ffmpeg version n4.3.1 Copyright (c) 2000-2020 the FFmpeg developers

We have successfully installed the latest stable version of FFmpeg.

3. Creating a Custom Palette

By default, FFmpeg uses a generic 256 color palette for every gif encoding. As a result, the output we get after converting the video is suboptimal. However, we can use FFmpeg itself to generate a custom palette of 256 colors created specifically for our video. After that, we can use the custom palette and the original video to create a higher quality gif.

Now, let’s generate the custom palette:

$ ffmpeg -ss 00:01:30 -t 5 -i video.mkv -filter_complex "[0:v] palettegen" palette.png

Let’s see what each option means:

  • -ss sets the starting point of the video
  • -t sets the duration. Therefore, we will eventually have a 5-second gif
  • -i specifies the input video file
  • -filter_complex is for applying filters. Here, we added the palettegen filter, which receives the first input video file (shown as [0:v]) as an argument

After running the above command, FFmpeg will create the custom palette named palette.png.

4. Creating the GIF

Now that we have generated our custom palette, we can use it to create the gif:

$ ffmpeg -ss 00:01:30 -t 5 -i video.mkv -i palette.png -filter_complex "[0:v] fps=10,scale=720:-1 [new];[new][1:v] paletteuse" output.gif

Let’s see what each new option does:

  • The second -i specifies the input custom palette
  • fps specifies the frame rate of the output gif
  • scale resizes the video. To clarify, the first parameter is the width and the second one is the height. We set the height to -1, which means we want to keep the aspect ratio. Therefore, it will be set automatically. Moreover, both fps and scale receive the video as input
  • paletteuse receives two arguments. The first argument is the output of fps and scale (shown as [new]), and the second argument is the custom palette we generated before

After running the above command, FFmpeg will create the gif.

5. Conclusion

In this article, we learned how to use the FFmpeg command-line tool to convert a video to a high-quality gif by generating a custom palette.

Comments are closed on this article!