How to Create High-Quality GIFs with FFmpeg

Standard GIF generation in FFmpeg often results in grainy, low-quality images because the GIF format is limited to a maximum of 256 colors. This article explains how to overcome this limitation by using FFmpeg’s palettegen and paletteuse filters. By utilizing this two-step process, you can generate a custom color palette tailored specifically to your input video, resulting in crisp, professional, and high-quality GIFs.

Understanding the Two-Step Process

The standard FFmpeg conversion uses a generic, static color palette, which leads to poor color representation and color banding. To solve this, FFmpeg offers two specific filters:

  1. palettegen: Analyzes the video frames and generates a highly optimized custom 256-color palette (saved as a PNG image).
  2. paletteuse: Applies this custom palette to the video during the GIF conversion, rendering the final output with accurate colors and smooth gradients.

You do not need to output a temporary palette file to your hard drive. You can link both filters together in a single FFmpeg command using a filtergraph. This is the fastest and most efficient way to generate high-quality GIFs.

Run the following command in your terminal:

ffmpeg -i input.mp4 -filter_complex "fps=15,scale=480:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" output.gif

Command Breakdown:


Method 2: The Two-Step Approach

If you prefer to inspect, edit, or reuse the generated palette file, you can run the process in two separate steps.

Step 1: Generate the Palette

Run this command to analyze the video and output a palette.png image:

ffmpeg -i input.mp4 -vf "fps=15,scale=480:-1:flags=lanczos,palettegen" -y palette.png

Step 2: Apply the Palette to the GIF

Run this command to merge the original video and the palette file into the final GIF:

ffmpeg -i input.mp4 -i palette.png -filter_complex "fps=15,scale=480:-1:flags=lanczos[x];[x][1:v]paletteuse" output.gif

Advanced Palette Tweaks

You can further customize how colors are processed by adding options to the filters.

Adjusting Dithering

Dithering helps smooth out color gradients, but it can increase the GIF’s file size. The paletteuse filter allows you to change the dithering mode.

To change the dither mode to Bayer, modify the filter like this:

[s1][p]paletteuse=dither=bayer:bayer_scale=3

To disable dithering completely:

[s1][p]paletteuse=dither=none