Is there a way to detect if an AVIF image is animated using plain JavaScript only?
How can I detect if AVIF image is animated?
375 Views Asked by John At
2
There are 2 best solutions below
0
On
Turns out this (seems to be) criminally easy with JavaScript.
Written in TypeScript for posterity:
/**
* Sniff for an animated AVIF byte
* @param buffer
* @returns boolean
* @example
* `return sniffAVIF(
* new Uint8Array(
* await uploadedFile.arrayBuffer()
* )
* )`
*/
const sniffAVIF = (view: Uint8Array) =>
return view[ 3 ] === 44;
Yes, really!
The first few bytes of every AVIF file (that I have tested at least) tend to look pretty much the same when loaded as a Uint8Array;
0, 0, 0, 44, 102, 116 for animated files
0, 0, 0, 28, 102, 116 for static files
So fairly trivial to discern one from the other. Of course, I have only been able to test this on a limited number of images, so please do feel free to correct me if you can find an AVIF that doesn't start with this series of bytes.
Hope this helps!
The new
ImageDecoderAPI can tell this to you.You'd pass a
ReadableStreamof your data to it, and then check if one of the decoder'strackshas itsanimatedmetadata set to true:However beware this API is still not widely supported, since only Chromium based browsers have an implementation currently.