js准确判断动态图片问题

问题: js有没有办法准确的判断图片地址以.gif结尾的图片一定是动态图片
因为有时候一些网站的图片是.gif后缀, 但是其实是静态图片

阅读 3.8k
2 个回答

搬运过来的,需要能获取到图片 blob 才可以这样判断

https://stackoverflow.com/que...

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

同学你放弃吧,因为真实的gif也有可能就是一帧, 当然不会动了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题