DEV Community

Halí
Halí

Posted on • Edited on • Originally published at halivert.dev

Convert mp4 to gif

We, dev people, have the need to post evidence of different behaviors of our desktop in many places (issues, documentation, blogs, etc.).

In this post, We'll learn how to convert an mp4 file to gif in two simple steps.

Requirements

Instructions

First, we need to extract the frames from our video. FFmpeg can do it with the next command:

ffmpeg -i video.mp4 -vf fps=5 frames/%03d.png
Enter fullscreen mode Exit fullscreen mode

The fps option defines the playback speed of the gif, I suggest between 5 and 6 to get closer to speed of the original video.

Then we "glue" the frames to make the gif.

convert frames/* output.gif
Enter fullscreen mode Exit fullscreen mode

With this, we have ready our gif, but maybe it's too big, so we can do the next step. Gif optimization.

convert output.gif -fuzz 1% -layers Optimize optimized.gif
Enter fullscreen mode Exit fullscreen mode

Extra

  1. For the naming part: %03d.png we need to multiply fps times seconds in the video, so, if our video lasts up to 166 seconds (2 minutes and 46 seconds) and we are using 6 fps, we can use %03d.png, but if the video is longer, it could be necessary change the names to %04d.png, in order to have the frames sorted.

  2. The fuzz percentage partly determines the optimized gif quality, that's why we use only 1%, you will notice that increasing that percentage will reduce the final quality.

Top comments (2)

Collapse
 
themilantej profile image
Milan Tejani

use this command:

ffmpeg -ss 30 -t 3 -i input.mp4 -vf "fps=10,scale=320👎flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 output.gif

Collapse
 
halivert profile image
Halí

Thank you for this shortcut 😌