j00b
j00b

Reputation: 405

How to determine the length of a .gif animation in milliseconds

Is there an easy way to figure out approximately how long a .gif image takes to play one time in Javascript?

Upvotes: 5

Views: 10603

Answers (4)

Irawati
Irawati

Reputation: 21

You can pass gif file to following function, which will return duration value

isGifAnimated(file) {
    return new Promise((resolve, reject) => {
      try {
        let fileReader = new FileReader();
        fileReader.readAsArrayBuffer(file);
        fileReader.onload = (event) => {
          let arr = new Uint8Array(<ArrayBuffer>fileReader.result);
          let duration = 0;
          for (var i = 0; i < arr.length; i++) {
            if (arr[i] == 0x21
              && arr[i + 1] == 0xF9
              && arr[i + 2] == 0x04
              && arr[i + 7] == 0x00) {
              const delay = (arr[i + 5] << 8) | (arr[i + 4] & 0xFF)
              duration += delay < 2 ? 10 : delay;
            }
          }
          resolve(duration / 100);
        }

      } catch (e) {
        reject(e);
      }
    });
  }

Upvotes: 2

AboulEinein
AboulEinein

Reputation: 1101

I tried ImageMagick identify but it didn't give me the correct duration.

I found another reliable way using ExifTool

exiftool -Duration image.gif

It will print out the duration in seconds:

Duration : 0.48 s

Upvotes: 1

Prinzhorn
Prinzhorn

Reputation: 22508

The accepted answer doesn't give the exact result. Elapsed time is like a real world clock while ImageMagick runs the animation. What you want is the Delay field for each frame and sum them up.

$ identify -verbose fail.gif  | grep Delay

Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 15x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 10x100
Delay: 33x100
Delay: 10x100
Delay: 10x100
Delay: 10x100

Where 33x100 is a delay of 330ms.

Edited by Mark Setchell

You can actually extract the delay parameter somewhat more surgically (than by using grep) with the %T escape:

enter image description here

identify -format "%T\n" animation.gif 

8
8
8
8
8
8
8
8
8
8
11
11
11
11
11
11
11
26

And get the total with awk like this:

identify -format "%T\n" anomation.gif | awk '{t+=$0} END{print t " centiseconds"}'
183 centiseconds

Upvotes: 2

Martin Vilcans
Martin Vilcans

Reputation: 5718

The identify command from ImageMagick can give this information:

$ identify -verbose file.gif | grep 'Elapsed time'

  Elapsed time: 0:01.080
  Elapsed time: 0:01.150
  Elapsed time: 0:01.230

...

  Elapsed time: 0:04.250
  Elapsed time: 0:04.330
  Elapsed time: 0:04.399
  Elapsed time: 0:04.480

The last line printed should be the total length of the animation.

Upvotes: 4

Related Questions