JS工具库:通过图片地址获取图片格式

116 阅读1分钟

JS工具库: 获取图片格式

解决问题:

  1. 图片地址后缀不是图片格式
  2. 图片后缀不是正确的图片格式
  3. 通过后缀获取格式不准确

// 获取图片格式
function getImageFormat(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = () => {
      const bytes = new Uint8Array(xhr.response);
      let format = null;
      if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
        format = 'jpg';
      } else if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {
        format = 'png';
      } else if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) {
        format = 'gif';
      } else if (bytes[0] === 0x42 && bytes[1] === 0x4d) {
        format = 'bmp';
      }
      if (format) {
        resolve(format);
      } else {
        reject(new Error('Unsupported image format'));
      }
    };
    xhr.onerror = () => {
      reject(new Error('Failed to load image'));
    };
    xhr.send();
  });
}