微信小程序压缩图片
1.wxml
<canvas class="canvas" style="width: {{cw0}}px; height: {{ch0}}px;" canvas-id="myCanvas0"></canvas>
2.js
Page({
/**
* 页面的初始数据
*/
data: {
scale: 0.5,
cw0: "",
ch0: ""
},
compress: function(e) {
let that = this;
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['camera'],
success(res) {
let path = res.tempFilePaths[0];
let size = res.tempFiles[0].size / 1024;
if (size > 100) { //大于100k压缩
wx.getImageInfo({
src: path,
success(res) {
//console.log('获得原始图片大小',res.width)
let originWidth, originHeight;
originHeight = res.height;
originWidth = res.width;
console.log(originWidth);
//压缩比例
// 最大尺寸限制
let maxWidth = originWidth * that.data.scale,
maxHeight = originHeight * that.data.scale;
// 目标尺寸
let 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大小
that.setData({
cw0: targetWidth,
ch0: targetHeight
});
let id = "myCanvas0";
//尝试压缩文件,创建 canvas
let ctx = wx.createCanvasContext(id);
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(path, 0, 0, targetWidth, targetHeight);
ctx.draw();
wx.showLoading({
title: "压缩中..."
})
//保存图片
setTimeout(function() {
wx.canvasToTempFilePath({
fileType: "jpg",
canvasId: id,
success: (res) => {
//写入图片数组
let uploadFile = res.tempFilePath;
that.uploadImg(uploadFile);
wx.hideLoading()
},
fail: (err) => {
console.error(err)
}
}, this)
}, 500);
}
})
} else {
that.uploadImg(path);
}
}
})
},
uploadImg: function(imgPath) {
let that = this;
let urlStr = "";//上传地址
wx.uploadFile({
url: urlStr,
filePath: imgPath,
name: "file",
success: function(res) {
},
fail: function(err) {
}
});
}
})
3.wxss
.canvas {
position: absolute;
left: -4000px;
}
隐藏canvas