Turn an animated GIF into a <video>

December 4th, 2024. Tagged: (x)HTML(5), ffmpeg, images


Animated gifs are fun and all but they can get big (in filesize) quickly. At some point, maybe after just a few low-resolution frames it's better to use an MP4 and an HTML <video> element. You also preferably need a "poster" image for the video so people can see a quick preview before they decide to play your video. The procedure can be pretty simple thanks to freely available amazing open source command-line tools.

Step 1: an MP4

For this we use ffmpeg:

$ ffmpeg -i amazing.gif amazing.mp4

Step 2: a poster image

Here we use ImageMagick to take the first frame in a gif and export it to a PNG:

$ magick "amazing.gif[0]" amazing.png

... or a JPEG, depending on the type of video (photographic vs more shape-y)

Step 3: video tag

<video width="640" height="480" 
  controls preload="none" poster="amazing.png">
  <source src="amazing.mp4" type="video/mp4">
</video>

Step 4: optimize the image

... with your favorite image-smushing tool e.g. ImageOptim

Comments

I did this for a recent Perfplanet calendar post and the 2.5MB gif turned to 270K mp4. Another 23MB gif turned to 1.2MB mp4.

I dunno if my ffmpeg install is to blame but the videos didn't play in QuickTime/FF/Safari, only in Chrome. So I ran them through HandBrake and that solved it. Cuz... ffmpeg options are not for the faint-hearted.

Do use preload="none" so that the browser doesn't load the whole video unless the user decides to play. In my testing without a preload=none Chrome and Safari send range requests (like an HTTP header Range: bytes=0-) for 206 Partial Content. Firefox just gets the whole thing

There is no loading="lazy" for poster images 🙁

Comments? Find me on BlueSky, Mastodon, LinkedIn, Threads, Twitter