美文网首页
图片尺寸比例和大小校验

图片尺寸比例和大小校验

作者: 芸芸众生ing | 来源:发表于2023-12-13 11:56 被阅读0次
    function getImageFileInfo(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.onerror = (e) => {
          console.error('读取异常')
          reject(false)
        }
        reader.onloadend = (e) => {
          let image = new Image();
          image.src = e.target.result;
          image.onload = () => resolve([image, e.target.result])
        }
        reader.readAsDataURL(file);
      })
    }
    function getImageSizeCheck(image, option) {
      function gcd(a, b) {
        if (b == 0) return a;
        return gcd(b, a % b)
      }
      const { width = 1920, height = 1080, size = 10240, ratio = 0.15 } = option || {};
      const { width: w, height: h, size: s } = image;
      const imgRatio = w / h; // 图片尺寸比例
      const optRatio = width / height; // 预设尺寸比例 
      let msg = '';
      if (size < s) msg = `图片需小于${size}KB,`;
      if (imgRatio > optRatio + ratio && imgRatio < optRatio - ratio) msg += `图片尺寸需符合${w}*${h}或${w / gys(w, h)}:${h / gys(w, h)}比例`;
      if (msg) throw new Error(msg);
      return true;
    }
    function gys(...args) {
      const [item, ...rest] = args;
      if (rest.length < 1) return a;
      if (rest.length === 1) {
        let a = item, b = rest[0];
        while (a > 0 && b > 0 && a != b) {
          if (a > b) a -= b;
          else b -= a;
        }
        return a
      }
      return gys(item, gys(...rest))
    }
    const [image, img] = await getImageFileInfo(file);
    getImageSizeCheck(image, { size: 1024, width: 1920, height: 1080 })

    相关文章

      网友评论

          本文标题:图片尺寸比例和大小校验

          本文链接:https://www.haomeiwen.com/subject/qqmbgdtx.html