1. 调用uni.chooseImage(OBJECT)选择图片(官网介绍:https://uniapp.dcloud.io/api/media/image );
2. 然后调用uni.getImageInfo(OBJECT)获取图片信息(官网介绍:https://uniapp.dcloud.io/api/media/image );
3. 根据获取到的图片宽高创建画布,可设置画布最大宽度;
4. 将图片画到canvas上面 使用Canvas中的drawImage()方法压缩(详细介绍和使用方法:https://www.w3school.com.cn/html5/canvas_drawimage.asp) ;
5. 使用canvas.toDataURL()方法将canvas画布转换为Base64编码的图片URL(详细介绍和使用方法:https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL);
6. 上传图片可使用uni.uploadFile(OBJECT)上传。
upload() {
var _this=this
uni.chooseImage({
count: 1, //默认9
sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
success: function (res) {
_this.imgPath = res.tempFilePaths.toString()
uni.getImageInfo({
src: _this.imgPath,
success: function (image) {
let canvasWidth = image.width //图片原始长宽
let canvasHeight = image.height;
let base = canvasWidth/canvasHeight;
//设置画布最大宽度
if(canvasWidth>800){
canvasWidth = 800;
canvasHeight = Math.floor(canvasWidth/base);
}
let img = new Image();
img.src = _this.imgPath; // 要压缩的图片
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// 清除画布
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// 将图片画到canvas上面 使用Canvas压缩
ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
// canvas.toDataURL 返回的是一串Base64编码的URL
// 指定格式 PNG
_this.imgPath = canvas.toDataURL("image/png");
}
});
}
});
},
uni.uploadFile({
url: 'https://www.example.com/upload', //仅为示例,非真实的接口地址
filePath: this.imgPath,
name: 'file',
formData: {
'user': 'test'
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
}
});