如何确定.gif动画的长度(以毫秒为单位)

时间:2012-03-21 20:47:22

标签: javascript image gif animated-gif

是否有一种简单的方法可以弄清楚.gif图片在Javascript中播放一次的时间大约需要多长时间?

4 个答案:

答案 0 :(得分:4)

来自ImageMagickidentify命令可以提供以下信息:

$ 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

打印的最后一行应该是动画的总长度。

答案 1 :(得分:2)

接受的答案没有给出确切的结果。 {Image =影像运行动画时,Elapsed time就像一个真实世界的时钟。你想要的是每帧的Delay字段并总结它们。

$ 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

33x100延迟330毫秒。

由Mark Setchell编辑

你实际上可以通过grep转义来更加手术地提取延迟参数(而不是使用%T):

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

以这样的awk得到总数:

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

答案 2 :(得分:1)

我尝试过ImageMagick identify,但它没有给我正确的持续时间。

我找到了另一种使用ExifTool

的可靠方法

exiftool -Duration image.gif

它会以秒为单位打印持续时间:

Duration : 0.48 s

答案 3 :(得分:0)

您可以将 gif 文件传递​​给以下函数,该函数将返回持续时间值

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);
      }
    });
  }