图片等比例缩放方法

export modifyImageSize = (path, maxWidth, maxHeight, callback) => {
  /*
   * @param path 【图片路径】
   * @param maxWidth 【允许缩放的最大宽度】
   * @param maxHeight 【 允许缩放的最大高度】
   * @parsm callback 【回调缩放高度宽度】
   */
  /*
    @使用方法
    
    modifyImageSize(path,500,500,(res)=>{
      let { tempHeight, tempWidth } = res
      console.log('缩放之后高度:'+tempHeight)
      console.log('缩放之后宽度:'+tempWidth)
    })
  */
  let image = new Image();
  image.src = path;
  var tempWidth;
  var tempHeight;
  image.onload = function() {
    if (image.width > 0 && image.height > 0) {
      if (image.width / image.height >= maxWidth / maxHeight) {
        if (image.width > maxWidth) {
          tempWidth = maxWidth;
          tempHeight = (image.height * maxWidth) / image.width;
        } else {
          tempWidth = image.width;
          tempHeight = image.height;
        }
      } else {
        if (image.height > maxHeight) {
          tempHeight = maxHeight;
          tempWidth = (image.width * maxHeight) / image.height;
        } else {
          tempWidth = image.width;
          tempHeight = image.height;
        }
      }
      callback({
        tempWidth, // 缩放之后宽度
        tempHeight // 缩放之后高度
      })
    }
  }
}
posted @ 2020-11-04 18:35  詹姆斯小皇帝  阅读(348)  评论(0编辑  收藏  举报