Create GIF with ffmpeg!

It seems generating GIF is more and more regular in our presentations. A reliable way to make it is important for us.

I tried PS, but I think the procedure is too tedious. Then I tried some small (online) tools, but these tools have no guarantee of quality.

Since ffmpeg is a cross-platform, open-source, well-tested tool, and it is quite useful for our other projects. In this article, I will describe how to create GIF with ffmpeg.

Install ffmpeg

The installation is easy. Go to Download FFmpeg.

Generate Gif from Images

The command line

ffmpeg -f image2 -framerate 1 -i imgs_%03d.jpg -loop -1 test.gif

notes:

  1. On windows: change ffmpeg to ffmpeg.exe, or wherever you install it. /path/to/ffmpeg.exe
  2. -f image2: for all the formats, you can refer here. But basically, image sequence use image2 is fine.
  3. -framerate: is to change the fps, the higher, the animation faster.
  4. -i: the input images. The image format can be common format like .jpg, .png, etc. It use %03d to format the name index. The usage of digit formating is the same with C language. %d means int, 03 means padding 0 to fill 3 digit. image_2.png should be image_002.png.
  5. -loop: if you do not use this, the default gif will loop forever. If you use -loop and follow a number N, it will loop N times. Someone says it loops N+1 times, but in my laptop, it loops N times.
  6. finally, the output name.

Generate Gif from Videos

In some cases, the gif is generated from videos. Or you simply want to split the videos into images.
You can use the following command.

ffmpeg -i test.mp4 -vf "select='not(mod(n,10))',setpts='N/(30*TB)'" -f image2 imgs_%03d.jpg

note: In this command, the only thing to look is the -vf option. it is to setup rules to filter the frames in videos. The complete usage can be referred to ffmpeg Documentation.

Gif with Transparency

The command above will result in a gif with black background.
To obtain a gif with transparency. You can use the following two commands.
Yes, it takes two to get what you want.

ffmpeg -i imgs_%03d.png -vf palettegen=reserve_transparent=1 palette.png
ffmpeg -framerate 30 -i imgs_%03d.png -i palette.png -lavfi paletteuse=alpha_threshold=128 -gifflags -offsetting test.gif