liubulong 发表于 2019-11-26 13:43:18

H5新属性实现图片压缩上传

在一次app项中,遇到了图片上传的问题,现在的智能手机图片都很大,用户体验很不好,这就需要压缩了,前端怎么实现了,强大的canvas提供了便捷方法:
html:<input type="file" accept="image/*" on-change="showFile($event)"/>
js:
function imgToBase64(file,maxLen,callBack){
    let img = new Image(),
      reader = new FileReader(),//读取文件
      fileType = file.type;//图片类型
    reader.onload = function (){
      let url = reader.result;//读取到的文件内容,这个属性值再读取操作完成之后才有效,且数据格式取决于读取操作是由哪个方法发起的,所以必须使用reader.onload
    }
    img.onload = function (){
      //图片原始尺寸
      let originWidth = img.width,
            originHeight = img.height,
            //最大尺寸限制
            maxWidth = 400 ,
            maxHeight = 400 ,
            //目标尺寸
            targetWidth = originWidth,
            targetHeight = originHeight;
      if(originWidth > maxWidth || originHeight > maxHeight){
            if(originWidth / originHeight > maxWidth / maxHeight){
                //更宽,按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            }else{
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
      }
      //生成canvas
      let canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d');
      canvas.width = targetWidth;
      canvas.height = targetHeight;
      ctx.drawImage(img,0,0,targetWidth,targetHeight);
      let base64 = canvas.toDataURL(fileType,0.92);//品质参数默认0.92,必须是格式为image/jpeg时才生效
      callBack(base64);
    }
    reader.readAsDataURL(file);

}
function showFile(e){
    let files = e.currentTarget.files;
    for(var i = 0;i<files.length;i++){
      imgToBase64(files,400,function(base64){
            //直接调用ajax上传base64就完成啦
            ajax....
      })
    }
}

页: [1]
查看完整版本: H5新属性实现图片压缩上传