裁剪base64图片

代码如下:

<canvas id="myCanvas" class="hidden"  ></canvas>
<img src="" alt="" class="varyPhoto width100"/>

js代码如下:

function mainEvent(base64){
  var img = new Image();
  img.src=base64;
  var canvas=document.getElementById("myCanvas");
  var ctx=canvas.getContext("2d");
  // 加载完成开始绘制
  var newBase64;
  MAX_HEIGHT = 1600;
  img.onload=function(){
    if(img.height > MAX_HEIGHT) {
      img.width *= MAX_HEIGHT / img.height;
      img.height = MAX_HEIGHT;
    }
    //准备canvas环境 
    canvas.width=img.width;
    canvas.height=img.height;
    // 绘制图片
    ctx.drawImage(img, 0, 0, img.width, img.height);
    newBase64=canvas.toDataURL('image/jpeg',0.6);//裁剪后的  0.6代表裁剪剩余60%
    //比较裁剪前后的base64图大小
    var oldSize=getImgSize(base64);
    var nowSize=getImgSize(newBase64);
    console.log("oldSize",oldSize)
    console.log("nowSize",nowSize)   
    $(".varyPhoto").attr("src",newBase64);//展示裁剪后的
  }
}

获取base64图片大小

function getImgSize(base64url) {
    //获取base64图片大小,返回KB数字
    var str = base64url;
    var strLength = str.length;
    var fileLength = parseInt(strLength - (strLength / 8) * 2);
    // 由字节转换为KB
    var size = "";
    size = (fileLength / 1024).toFixed(2);  
    return parseInt(size);
}

 

posted @ 2022-08-01 10:40  阳光下的向日葵  阅读(244)  评论(0编辑  收藏  举报