微信小程序利用Canvas 2D 接口实现图片等比例压缩(附源码)
图片上传到后台服务器,如果图片过大,就是导致上传时间长、占据内存大,利用微信小程序官方压缩图片接口(wx.compressImage)一容易导致图片失真;二ios系统不支持png格式图片压缩;其次就是压缩质量数值过大,根本满足不了压缩图片大小的要求,所以利用官方Canvas 2D接口压缩图片。
源码如下,经过调试,可以直接复用,有问题可以指出来,互相交流。
* wxml代码*
因为引用canvas组件只是为了实现图片压缩,所以不在页面上展示
<canvas type="2d" id="canvas_compress" style="width: {{canvasCompresswidth}}px; height: {{canvasCompressheight}}px;position: absolute; z-index: -1; left: -10000rpx;top: -10000rpx;" />
js代码*
Page({
/** 页面的初始数据 */
data: {
ImageUrl:"/weixin/add.png",
canvasCompresswidth:"",
canvasCompressheight:"",
imgPath:"",
pathImage:"",
}
UpHeadImage:function(){
const _this = this;
wx.chooseMedia({//选择照片
count:1,//选择照片数量
mediaType:['image'],//只能上传图片
sourceType:['album','camera'],//可通过相册或者照相机上传
success:(res)=>{
console.log("1、图片上传结果",res)
let imgPath = res.tempFiles[0].tempFilePath;
this.setData({
imgPath:imgPath
})
console.log('图片临时地址',this.data.imgPath)
wx.getImageInfo({//获取照片信息
src:imgPath,
success(res){
console.log("2、图片信息",res)
let width=res.width;
let height=res.height;
while( width > 720 || height > 960){//如果照片分辨率高>960或者宽>720进行等比例压缩,可以根据自己需要进行修改
if(width>720){
const ratio=width/720;
width=720;
height=height/ratio;
}else if(height>960){
const ratio=height/960;
height=960;
width=width/ratio;
}
}
_this.setData({
canvasCompresswidth:width,
canvasCompressheight:height
})
console.log("canvas的宽高",_this.data.canvasCompresswidth,_this.data.canvasCompressheight)//canvas宽高
wx.createSelectorQuery()
.select('#canvas_compress')
.fields({node:true,size:true})
.exec((res)=>{
console.log("canvas对象",res)
// Canvas 对象
const canvas=res[0].node;
// Canvas 绘制上下文
const ctx =canvas.getContext('2d');
// 初始化画布大小
const dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = width * dpr;
canvas.height = height * dpr;
ctx.scale(dpr,dpr);
const image =canvas.createImage();//进行绘图
image.src= _this.data.imgPath;
image.onload=()=>{
ctx.drawImage(image,0,0,width,height);
wx.canvasToTempFilePath({//生成图片
canvas:canvas,
destWidth:width,
destHeight:height,
fileType:'jpg',//绘制图片输出格式
success:(res)=>{
/***
将绘制的图片上传到后台服务器
**/
},
fail(error){
console.log('生成图片出错了!',error)
}
})
}
})
},
fail(res){
console.log("错误信息",res)
}
})
}
})
},
})
图片信息绘制前后对比