Ubuntu – How to create a 30 second GIF from a long random video

.mp4ffmpeggif

I have hundreds of videos in a folder that I want to make a gif for. Each videos length is different but all videos are longer than 30 seconds. I want to take 10 3 second gif images from a video over the course of the video. For example if the video is 25 minutes long a 3 second recorded gif should be taken every 2.5 minutes (150 seconds).

The finished gifs must also have the same name as the video but ending in .gif all videos are .mp4

The gifs should be 560×340

It would be nice to do this with one command to.

Best Answer

Steps:

  1. Get duration with ffprobe.
  2. Use duration as a value in the select filter.
  3. Create gif.
  4. Script everything.

Example script:

#!/bin/bash
mkdir 30gif
for f in *.mp4; do
  duration=$(ffprobe -loglevel error -show_entries format=duration -of default=nk=1:nw=1 "$f")
  ffmpeg -i "$f" -filter_complex "[0:v]select='lt(mod(t,${duration}/10),3)',setpts=N/(FRAME_RATE*TB),scale=560:340:force_original_aspect_ratio=decrease,pad=560:340:(ow-iw)/2:(oh-ih)/2,setsar=1,split[v0][v1];[v0]palettegen[p];[v1][p]paletteuse[v]" -map "[v]" "30gif/${f%.mp4}.gif"
done

This fulfills your many requirements:

  • Output 30 second GIF comprising of 3 second segments equally spanning input duration
  • 560x340 output size
  • One (ffmpeg) command
  • Using a bash for loop so you can automatically convert hundreds of videos
  • Output name is same as input name but with .mp4 replaced with .gif
Related Question