← Back to Tiny Hacks

Convert an MP4 file to a GIF file using ffmpeg

Install ffmpeg (my preferred way to install ffmpeg is to use Chocolateyhttps://chocolatey.org/packages/ffmpeg). Then use the following command to convert the mp4 file (say input.mp4) into gif file (say output.gif)

ffmpeg -i input.mp4 output.gif

Ffmpeg has a ton of options you can use to customize the output. For example: 

ffmpeg -i input.mp4 -t 3 -vf "fps=10, scale=500:-1" output.gif 

will create a 3 second gif (-t 3) and set the frame rate at 10 frames per second and resize the output to be 500px wide while autoscaling the height (-vf "fps=10, scale=500:-1).

The complete list of ffmpeg options are available here: https://ffmpeg.org/ffmpeg.html and https://ffmpeg.org/ffmpeg.html#Video-Options.

gif to mp4

For the reverse, this command has worked well for me: 

ffmpeg -i animated.gif -movflags faststart -pix_fmt yuv420p -vf "scale=trunc
(iw/2)*2:trunc(ih/2)*2" video.mp4

ref: https://rigor.com/blog/optimizing-animated-gifs-with-html5-video