Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: November 26, 2022
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.
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.
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:
After running the above command, FFmpeg will create the custom palette named palette.png.
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:
After running the above command, FFmpeg will create the gif.
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.