I tried to show gif only one time. So I used this code to achieve this.
var ui_img = document.getElementById("ui_image");
ui_img.hidden = false;
setTimeout(function () {
ui_img.hidden = true;
}, 8000);
But I knew the all gifs do not have the same duration. How can I solve this?
You could try using this library gifuct-js.
Mainly use parseGIF()
, then decompressFrames()
to get an array of frames each having the property delay
: the amount of time the frame is shown. So, you could sum up all the frame delays to get the total duration of a GIF image.
Usage example - Modified code sample from its Github page:
import { parseGIF, decompressFrames } from 'gifuct-js'
var oReq = new XMLHttpRequest();
oReq.open("GET", gifURL, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
var gif = parseGIF(arrayBuffer);
var frames = decompressFrames(gif, true);
// do something with the frame data
// get total time in ms
var totalTime = frames
.map(frame => frame.delay)
.reduce((a, b) => a + b);
}
};
oReq.send(null);
If i could improve upon @Alex code i would have made it Sync instead and more generaled purpose to work with mostly any source and not lock it into only working with only files (and also avoiding long unnecessary promise chains)
I would only accept a Uint8array
that could have a byte offset and being part of a larger zip file or something...
That way it can work with eg NodeJS filesystem & fetch
too.
I would also have used blob.arrayBuffer()
instead of using the legacy FileReader
fetch('https://media0.giphy.com/media/FIHThOlkZK3r8HTj9t/giphy.gif')
.then(res => res.arrayBuffer())
.then(ab => isGifAnimated(new Uint8Array(ab)))
.then(console.log)
/** @param {Uint8Array} uint8 */
function isGifAnimated (uint8) {
let duration = 0
for (let i = 0, len = uint8.length; i < len; i++) {
if (uint8[i] == 0x21
&& uint8[i + 1] == 0xF9
&& uint8[i + 2] == 0x04
&& uint8[i + 7] == 0x00)
{
const delay = (uint8[i + 5] << 8) | (uint8[i + 4] & 0xFF)
duration += delay < 2 ? 10 : delay
}
}
return duration / 100
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With