Converting animgif to WebM/H.264 video
The ImageOptim API provides high-quality conversion of animated GIFs to efficient WebM or H.264 files:
- applies intelligent filtering to reduce dithering and banding distortions often found in GIF video clips,
- and encodes video with extra color sharpness to preserve crisp look of simple GIF animations.
The conversion reduces file sizes dramatically (5-10×), and often improves quality as well!
(these are screenshots, click to open the clips)
|
|
Fat, 8-bit-color GIF source | WebM from the API — nicer and 8 times faster! |
Requesting conversion
Make an API POST request, or upload the GIF file with the format=webm
(or format=h264
) option. Example API URL: https://im2.io/eX4mp1E4pI/format=webm/example.com/meme.gif
. More how to make the request.
Save video file obtained from the API on your server (e.g. in the same directory where GIF files are stored). The file should have .webm
filename extension (or .mp4
for H.264).
Change your page's markup to use both GIF and video (example below).
Limitations
Animated GIF files can be quite large, so the conversion may take 30 seconds or even longer. In case you get HTTP timeout errors, please configure your HTTP client to allow longer timeouts.
Compatibility
The WebM format is supported by Chrome, Firefox, Microsoft Edge, Opera, and Chrome for Android. The H.264 format is required for Internet Explorer and Safari.
By the way, ImageOptim API supports also GIF optimizations. You can optimize the fallback animation, too (to do that, omit format=webm
).
Serving both GIF and video
It's possibe to automatically use video in browsers which support it, and gracefully fall back to GIF if they not. We recommend the following approach:
This script needs to be placed only once on the page:
<script> function gifFallback(source) {
var video=source.parentNode;
video.outerHTML='<img src="'+video.querySelector('a').href+'">';
} </script>
And then, later on the page, GIFs can be embedded like this (change highlighted filenames to point to your files):
<video autoplay loop muted playsinline>
<source src='clip.webm'
type='video/webm; codecs="vp9"' onerror="gifFallback(this)">
<a href='clip.gif'>Play</a>
</video>
Technical details about this code: in the fallback GIF is the markup as a link, not an <img>
, because browsers load all images unconditionally, even when the video works, which is a huge waste of bandwidth. The extra bit of JavaScript ensures reliable and efficient fallback.