最近需求就是通过微信小程序上传图片给后端,废话不多说直接上代码:
xml代码如下:
<canvas canvas-id='photo_canvas' style='position:fixed;left: 9999px;width:500px;height:{{ canvasHeight }}px' class='myCanvas'></canvas>
js代码如下:
data中会定义如下几个字段 主要是 picturePathLocal 和 yasuo 其他看自己需求是否使用
通过点击 choosePic 方法 (如上上图所示)
//选择图片
choosePic: function (e) {
var that = this;
wx.chooseImage({
count: 1, // 默认1
sizeType: ['original'], // 因为下面走压缩了,这里就原图上传
// sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
that.compressImage(res.tempFilePaths[0], (res1) => { // 压缩方法 在下面请提取
that.setData({
showPic: false,
itemhide:true,
yasuo:res1,//这个是压缩的地址
picturePathLocal:res.tempFilePaths[0]//这个是没压缩的地址
});
});
// console.log(res)
}
})
},
接下来写压缩图片方法:
// 压缩图片
compressImage(path, callback) {
var that = this;
//获取图片信息
console.log("path==",path)
wx.getImageInfo({
src: path,
success: function (res) {
var ctx = wx.createCanvasContext('photo_canvas'); // 创建画布
var towidth = 500; //设置canvas尺寸,按宽度500px的比例压缩
var toheight = Math.trunc(500*res.height/res.width); //根据图片比例换算出图片高度
that.setData({ canvasHeight: toheight });
ctx.drawImage(path, 0, 0, res.width, res.height, 0, 0, towidth, toheight);
ctx.draw(false, function () {
wx.canvasToTempFilePath({
canvasId: 'photo_canvas',
fileType:"jpg",
quality: 0.8, // 注意你的压缩质量,卤煮真的压缩出20KB的,图片整个都是糊的
success: function (res) {
// console.log("压缩图片===",res.tempFilePath);
callback(res.tempFilePath);
},
fail: function (res) {
// console.log("报错===",res.errMsg)
}
}, this)
})
}
});
},
然后通过自己需求点击上传按钮实现压缩的路径给后台
如果还是不会的话评论留言给你解答。。。。。。。