You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Tampermonkey中检测无后缀URL图片是否为GIF的方法

检测无后缀URL的图片是否为GIF的可行方法
  • 用XMLHttpRequest/GM_xmlhttpRequest获取二进制数据校验文件头
    Tampermonkey环境中fetch可能受限,但XMLHttpRequest或脚本专属的GM_xmlhttpRequest基本都能正常使用。GIF格式有固定的文件头标识(GIF87a或GIF89a),只需读取返回数据的前6个字节即可判断:
function isGifImage(imgUrl) {
  return new Promise((resolve, reject) => {
    // 若存在跨域问题,改用GM_xmlhttpRequest并添加// @grant GM_xmlhttpRequest到脚本开头
    GM_xmlhttpRequest({
      method: 'GET',
      url: imgUrl,
      responseType: 'arraybuffer',
      onload: function(response) {
        if (response.status === 200) {
          const buffer = new Uint8Array(response.response);
          const gifSignature = String.fromCharCode(buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);
          resolve(gifSignature === 'GIF87a' || gifSignature === 'GIF89a');
        } else {
          reject(new Error('请求图片失败'));
        }
      },
      onerror: reject
    });
  });
}

// 使用示例
isGifImage('目标图片URL')
  .then(isGif => console.log('是否为GIF:', isGif))
  .catch(err => console.error(err));
  • 结合Image对象与canvas检测动态GIF(仅适用于动态场景)
    如果只需识别动态GIF,可以加载图片后尝试读取不同帧的像素数据。静态GIF和普通图片无法通过此方法区分,但动态GIF的帧数据会存在差异:
function isAnimatedGif(imgUrl) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = function() {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;
      
      // 获取第一帧数据
      ctx.drawImage(img, 0, 0);
      const firstFrame = ctx.getImageData(0, 0, img.width, img.height).data;
      
      // 尝试跳转到第二帧(仅GIF动画支持seek方法)
      img.seek?.(1);
      ctx.drawImage(img, 0, 0);
      const secondFrame = ctx.getImageData(0, 0, img.width, img.height).data;
      
      // 比较帧数据是否不同
      let isAnimated = false;
      for (let i = 0; i < firstFrame.length; i++) {
        if (firstFrame[i] !== secondFrame[i]) {
          isAnimated = true;
          break;
        }
      }
      resolve(isAnimated);
    };
    img.onerror = reject;
    img.src = imgUrl;
  });
}

注意:Image.seek方法兼容性有限,仅作为文件头校验方法的补充方案。

内容的提问来源于stack exchange,提问作者alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 14:18:10