Better than animated gif

Converting animated GIFs to MP4 with FFmpeg MP4 videos have near-universal support. And they are smaller and better than animated GIFs from a performance perspective. But how easy is it to create and share MP4 videos online? Luckily the answer is pretty easy!

We can use ffmpeg, a free, open source command line tool to convert an animated GIF into an MP4 video. Make sure you download a pre-built package unless you are nerdy enough to build from source. In the example below we use FFmpeg to convert the file animated.gif into an MP4 video named video.mp4 - rigor.com

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

I know that looks intimidating, but don’t worry; those extra options ensure we have a nice, fast, compatible video file that will play anywhere. Here is what they do:

- movflags – This option optimizes the structure of the MP4 file so the browser can load it as quickly as possible. I’ll talk about this optimization more in a future blog post. - pix_fmt – MP4 videos store pixels in different formats. We include this option to specify a specific format which has maximum compatibility across all browsers. (This is actually the chroma subsampling we mentioned earlier). - vf – MP4 videos using H.264 need to have a dimensions that are divisible by 2. This option ensures that’s the case. Don’t worry, we can still display this video at any dimensions you want.

Now that we have a video file instead of an image, our HTML markup needs to change. Our original markup to include an animated GIF looked like this:

<img src="vid.gif" alt="" width="400" height="300"/>

To use our new video, we need to replace that with this:

<video autoplay="autoplay" loop="loop" width="400" height="300"> <source src="video.mp4" type="video/mp4" /> <img src="video.gif" width="400" height="300" /></video>