是否可以检测动画gif图像客户端?

doe*_*man 16 javascript

是否可以检测动画gif图像客户端?

在Internet Explorer中,您可以使用此onload事件,因为它将在每个加载的帧中触发(在IE8中更改了行为).

但是其他浏览器也有办法吗?

lak*_*nen 14

我刚刚写了一些可以检测GIF动画的JS.适用于IE 9以外的大多数现代浏览器.

免责声明:仅当图像的域来源与您从中加载脚本的页面相同时,此方法才有效.

请参阅要点以获取最新版本的代码:https://gist.github.com/3012623

function isAnimatedGif(src, cb) {
    var request = new XMLHttpRequest();
    request.open('GET', src, true);
    request.responseType = 'arraybuffer';
    request.addEventListener('load', function () {
        var arr = new Uint8Array(request.response),
            i, len, length = arr.length, frames = 0;

        // make sure it's a gif (GIF8)
        if (arr[0] !== 0x47 || arr[1] !== 0x49 || 
            arr[2] !== 0x46 || arr[3] !== 0x38)
        {
            cb(false);
            return;
        }

        //ported from php http://www.php.net/manual/en/function.imagecreatefromgif.php#104473
        //an animated gif contains multiple "frames", with each frame having a 
        //header made up of:
        // * a static 4-byte sequence (\x00\x21\xF9\x04)
        // * 4 variable bytes
        // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)
        // We read through the file til we reach the end of the file, or we've found 
        // at least 2 frame headers
        for (i=0, len = length - 9; i < len, frames < 2; ++i) {
            if (arr[i] === 0x00 && arr[i+1] === 0x21 &&
                arr[i+2] === 0xF9 && arr[i+3] === 0x04 &&
                arr[i+8] === 0x00 && 
                (arr[i+9] === 0x2C || arr[i+9] === 0x21))
            {
                frames++;
            }
        }

        // if frame count > 1, it's animated
        cb(frames > 1);
    });
    request.send();
}
Run Code Online (Sandbox Code Playgroud)


Res*_*uum 0

我不知道有什么方法可以在客户端做到这一点,但我对此也不确定。您可以做的是解析服务器端的 HTML 代码和任何引用的 gif,并向这些图像添加一个类。但实际上并不推荐这样做,因为它至少涉及对 HTML 的额外解析 + 对每个 gif 的解析。正如您从PHP 示例中看到的,检查 gif 在 CPU 负载方面也并非微不足道。