Search code examples
javascriptavif

How can I detect if AVIF image is animated?


Is there a way to detect if an AVIF image is animated using plain JavaScript only?


Solution

  • The new ImageDecoder API can tell this to you.

    You'd pass a ReadableStream of your data to it, and then check if one of the decoder's tracks has its animated metadata set to true:

    if (!window.ImageDecoder) {
      console.warn("Your browser doesn't support the ImageDecoder API yet, we'd need to load a library");
    }
    // from https://colinbendell.github.io/webperf/animated-gif-decode/avif.html
    fetch("https://colinbendell.github.io/webperf/animated-gif-decode/6.avif").then((resp) => test("animated", resp.body));
    // from https://github.com/link-u/avif-sample-images cc-by-sa 4.0 Kaede Fujisaki
    fetch("https://raw.githubusercontent.com/link-u/avif-sample-images/master/fox.profile1.8bpc.yuv444.avif").then((resp) => test("static", resp.body));
    
    document.querySelector("input").onchange = ({target}) => test("your image", target.files[0].stream());
    
    
    async function test(name, stream) {
      const decoder = new ImageDecoder({ data: stream, type: "image/avif" });
      // wait for we have some metadata
      await decoder.tracks.ready;
      // log if one of the tracks is animated
      console.log(name, [...decoder.tracks].some((track) => track.animated));
    }
    <input type=file>

    However beware this API is still not widely supported, since only Chromium based browsers have an implementation currently.