Skip to main content

High-Quality GIFs with FFmpeg: A Two-Step CLI Guide

·298 words·2 mins
Author
psilore
Lead developer and systems engineer. Passionate about retro computing, Linux environments, and automation frameworks.

Tired of grainy, pixelated GIFs that look like they were made in 1995? With FFmpeg, you can generate crisp, high-quality GIFs from any video in just two simple commands.

With a bit of fine-tuning, you can achieve incredibly clean, near-lossless GIF quality. The secret lies in generating a custom color palette of the video before encoding.


The Two-Step FFmpeg Process
#

Instead of using a generic 256-color palette, we generate an optimized color palette specifically tailored to the colors used in our source video.

Step 1: Analyze and Create the Palette
#

First, scan the input video (e.g., video.mp4 or dump.webm) and generate a custom palette image:

ffmpeg -i dump.webm -filter_complex "[0:v] palettegen" palette.png

Step 2: Render the GIF using the Palette
#

Next, apply that custom palette to convert the video into a high-quality GIF:

ffmpeg -i dump.webm -i palette.png -filter_complex "[0:v][1:v] paletteuse" dump.gif

Automate It: The gifify Script
#

Manually running two commands every time is tedious. Let’s wrap it in a clean Bash script to automate the entire workflow.

#!/bin/bash
# gifify.sh - Convert video to a high-quality GIF in one go

if [ -z "$1" ]; then
    echo "Usage: ./gifify.sh input_video.mp4"
    exit 1
fi

INPUT_FILE="$1"
OUTPUT_FILE="${INPUT_FILE%.*}.gif"
PALETTE_TEMP="/tmp/palette.png"

# 1. Generate custom palette
ffmpeg -y -i "$INPUT_FILE" -filter_complex "[0:v] palettegen" "$PALETTE_TEMP"

# 2. Encode video as GIF using the palette
ffmpeg -y -i "$INPUT_FILE" -i "$PALETTE_TEMP" -filter_complex "[0:v][1:v] paletteuse" "$OUTPUT_FILE"

# Clean up
rm "$PALETTE_TEMP"

echo "Success! GIF created at: $OUTPUT_FILE"
Pro Tip: Add this script to your local bin directory (/usr/local/bin/gifify or ~/bin/gifify), and you can convert any video file instantly from anywhere in your terminal!

How do you make GIFs?
#

Do you use FFmpeg for quick media tasks, or do you prefer GUI-based tools? Let’s share some command-line recipes in the comments!