DEV Community

Christopher Konopka
Christopher Konopka

Posted on

Generate GIFs from a directory of videos using FFmpeg

gif

Background

As a video artist I deal with many physical formats (analog composite to 4K) and digital formats (.mp4, .mov, Motion JPEG, .gif, etc.). Going between formats can be a nightmare, and I like to build tools that can ease any potential stress. Over the summer, I wanted to convert my analog video synthesis into .gif files to upload to Giphy. So I made this bash script that ingests a directory of video content and asks for a target file format.

Breakdown

Create a new bash script named dir-gen-gif.sh.

# dir-gen-gif.sh
#!/bin/bash

Ask for a directory of video content.

echo "Provide a directory please :"
read dir

Ask for a video file format.

echo "Filetype?"
read filetype

Create a loop that iterates over the directory and finds the target video file format.

for f in $dir/*.$filetype
do
    echo "Processing $f"
    # ... ffmpeg code
done

Add the FFmpeg scripts. First create a .png analysis file and then generate a .gif file.

    # Generate .png analysis file
    ffmpeg -y -ss 0 -t 11 -i $f -filter_complex "[0:v] palettegen" "${f%.*}.png"
    # Create .gif file
    ffmpeg -ss 0 -t 11 -i $f -filter_complex "[0:v] fps=24,scale=w=480:h=-1,split [a][b];[a] palettegen=stats_mode=single [p];[b][p] paletteuse=new=1" "${f%.*}.gif"

And the process will look something like this ...

gif

Reference

# dir-gen-gif.sh
#!/bin/bash

# Provide a directory containing video files 
echo "Provide a directory please :"
read dir

# Filetype target
echo "Filetype?"
read filetype

# Iterate over the directory, look for target filetype
for f in $dir/*.$filetype
do
    echo "Processing $f"
    # Generate .png analysis file
    ffmpeg -y -ss 0 -t 11 -i $f -filter_complex "[0:v] palettegen" "${f%.*}.png"
    # Create .gif file
    ffmpeg -ss 0 -t 11 -i $f -filter_complex "[0:v] fps=24,scale=w=480:h=-1,split [a][b];[a] palettegen=stats_mode=single [p];[b][p] paletteuse=new=1" "${f%.*}.gif"
done

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post