图片限制分辨率vue js

需求:系统要做个性化系统logo,不限制分辨率会显得非常丑,于是按照分辨率提交图片。

实现

封装函数:


//限制图片尺寸
const limitFileWH = (E_width: Number, E_height: Number, file: any) => {
  let _this = this;
  let imgWidth = 0;
  let imgHeight = 0;
  const isSize = new Promise(function (resolve, reject) {
    let width = E_width;
    let height = E_height;
    let _URL = window.URL || window.webkitURL;
    let img = new Image();
    img.onload = function () {
      imgWidth = img.width;
      imgHeight = img.height;
      let valid = img.width == width && img.height == height;
      valid ? resolve() : reject();
    }
    img.src = _URL.createObjectURL(file);
  }).then(() => {
    if (imgHeight !== E_height && imgWidth !== E_width) {
      hlAlert("请上传jpg、jpeg、png格式的图片,分辨率限制为" + E_width + '*' + E_height);
      return false;
    } else {
      return true;
    }
  }, () => {
    hlAlert("请上传jpg、jpeg、png格式的图片,分辨率限制为" + E_width + '*' + E_height);
    return false;
  });
  return isSize;
}

调用:(分辨率正确发起请求)这里使用了el-upload,提交前检查


//el-upload上传图片检查
beforeAvatarUpload: async (file) => {
  //调用[限制图片尺寸]函数 这里限制图片为368*104
   let res = await hlLimitFileWH(368, 104, file);
   return res;
 }

猜你喜欢

转载自blog.csdn.net/enhenglhm/article/details/128965176