canvas实现图片压缩

有时候页面上传的图片太大,难以进行图片识别,就需要在传给接口前先做压缩的处理,使用canvas进行图片压缩可以等比例压缩,不会出现失真模糊的情况。

/**
*imgData 原图base64
*imgSize 原图实际大小
*compressWidth 压缩后图片宽度
*flag 强制压缩到指定大小
*needRate 需要被压缩到的大小
*/
compressFn = (imgData, imgSize, compressWidth,flag,needRate)=>{
  let img = new Image();
  let maxW = compressWidth;
  img.src = imgData;
  img.onload = ()=>{
    let cvs = document.createElement('canvas');
    let ctx = cvs.getContext('2d');
    if(img.width > maxW){
      img.height *= maxW/img.width;
      img.width = maxW;
    }
    let w = img.width;
    let h = img.height;
    if(w < 400){
      cvs.height = h*(400/w);
      cvs.width = 400;
    }else{
      cvs.height = h;
      cvs.width = w;
    }
    ctx.fillStyle='#fff';
    ctx.fillRect(0,0,cvs.width,cvs.height);
    ctx.drawImage(img,0,0,img.width,img.height);
    let compressRate = compressRate(0.293,imgSize);
    if(compressRate<0.3){
      compressRate = 0.3;
    }
    let resImgData = cvs.toDataURL('image/jpeg',compressRate);
    let ss = resImgData.length/1024/1024;
    // 假如压缩不到30k,通过缩小画布的方式继续压缩
    if(flag&&ss>needRate){
      cvs=scaleCanvas(cvs,0.5,0.5);
      resImgData=cvs.toDataURL('image/jpeg',0.5);
      var nns = resImgData.length/1024/1024;
      if(nns>needRate){
        cvs=scaleCanvas(cvs,0.5,0.5);
        resImgData=cvs.toDataURL('image/jpeg',0.5);
      }
    }
    ctx.clearRect(0,0,cvs.width,cvs.height);
    cvs=null;
    return resImgData;
  }
}

等比例缩小画布

scaleCanvas=(canvas,scaleX,scaleY)=>{
  let sc=document.createElement('canvas');
  sctx=sc.getContext('2d');
  sc.width=canvas.width*scaleX;
  sc.height=canvas.height*scaleY;
  scx.scale(scaleX,scaleY);
  scx.lineCap='round';
  scx.lineJoin='round';
  scx.fillStyle='rgba(255,255,255,0)';
  scx.drawImage(canvas,0,0);
  scx.closePath();
  return sc;
}

获取压缩比例

compressRate=(needSize,oldFileSize)=>{
  let rate=1;
  if(oldFileSize/needSize >4){
    rate=0.5;
  }else if(oldFileSize/needSize >3){
    rate=0.6;
  }else if(oldFileSize/needSize >2){
    rate=0.7;
  }else if(oldFileSize > needSize){
    rate=0.8;
  }else{
    rate=0.9;
  }
  return rate;
}
posted @ 2022-09-01 18:42  阿伊的碎碎念  阅读(365)  评论(0编辑  收藏  举报