Prabhakar Kasi iOS Developer, Front End Developer

Create gifs from video using ffmpeg

1 min read

Use ffmep to create GIFs from Video

There a times we want to create gifs out of a video. I extensively need this at work as git did not support video uploads until recently. In order add demo video, I would create gifs from the recorded video. This tool was super easy and helpful until the update from git. Now this tool is used for creating gifs in presentation.

Setup

  1. Install homebrew – https://brew.sh/
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Once installation completes, read the closing notes. It might ask you run few commands like this.
    echo '# Set PATH, MANPATH, etc., for Homebrew.' >> /Users/pkasi/.zprofile
    echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/pkasi/.zprofile
    eval "$(/opt/homebrew/bin/brew shellenv)"
  1. Install ffmpeg – https://ffmpeg.org/download.html
brew install ffmpeg
  1. Add a alias function in your editor script

You can modify the scale specified in makegifHD and makegifLQ function if needed but 400 (max-width) seemed to give good result for phone-simulator recorded videos.

Open vi ~/.zshrc or vi ~/.bashrc or vi ~/.bash_profile
  (Append the script below to the end of the file)

# Helper function for making gifs using ffmpeg
function makegif {
  ffmpeg -y -i $3 -vf fps=$1,scale=$2:-1:flags=lanczos,palettegen palette.png
  ffmpeg -y -i $3 -i palette.png -filter_complex "fps=$1,scale=$2:-1:flags=lanczos[x];[x][1:v]paletteuse" $3.gif
}

function makegifHD {
  ffmpeg -y -i $1 -vf fps=30,scale=400:-1:flags=lanczos,palettegen palette.png
  ffmpeg -y -i $1 -i palette.png -filter_complex "fps=30,scale=400:-1:flags=lanczos[x];[x][1:v]paletteuse" $1.gif
}

function makegifLQ {
  ffmpeg -filter_complex "[0:v] fps=12,scale=360:-1,split [a][b];[a] palettegen [p];[b][p] paletteuse" -i $1 $1.gif
}
  1. Run the script to create gifs from videos

makegif function takes 3 arguments

  • fps – Frames per second. Higher value means file size will be bigger but you get more crisper details. Based on my experience, even 10 fps gave good results from videos recorded using QuickTime player.
  • scale – Video scale option. Scale will resize the video maintaining the aspect ratio. Setting width of 400 gave high quality for phone-simulator recorded videos. If you need smaller filesize, then you can set a low value. If video size is in movie format please use corresponding value.
  • input filename – full path of the input file
makegif 16 400 filename.mp4

makegifHD and makegifLQ function takes 1 argument

  • input filename – full path of the input file
GIF created using video
Video was 1080p -> makegif 10 1200 filename.m4v

Reference

  1. https://ffmpeg.org/ffmpeg.html
  2. https://ffmpeg.org/ffmpeg-filters.html#scale
  3. https://www.baeldung.com/linux/bash-alias-vs-script-vs-new-function
Prabhakar Kasi iOS Developer, Front End Developer

Leave a Reply