html部分
<canvas canvas-id="canvas" id="canvas"
style="position:absolute;left:-10000px;top:-10000px"
:style="{width:cWidth+'px',height:cHeight+'px'}"></canvas>
js部分:
data() {
return {
cWidth:0,
cHeight:0
}
},
method:{
chooseImage(){
uni.chooseImage({ //选择照片或者时拍照上传
count: num,
sizeType: ['original', 'compressed'],
sourceType: ['camera'],
success: res=>{
const tempFilePaths = res.tempFilePaths
// #ifdef H5
this.recursionCompressH5(tempFilePaths[0],res=>{
this.upLoadImgs(res)
})
// #endif
// #ifndef H5
this.recursionCompressMP(tempFilePaths[0],res=>{
this.upLoadImgs(res)
})
// #endif
}
});
} ,
recursionCompressMP(url, callback) {
let that = this;
uni.getImageInfo({
src: url,
success (res) {
var originWidth, originHeight;
originHeight = res.height;
originWidth = res.width;
console.log(originWidth);
//压缩比例
// 最大尺寸限制
var maxWidth = 750,
maxHeight = 1200;
// 目标尺寸
var 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));
}
}
that.cWidth = targetWidth
that.cHeight = targetHeight
var ctx = uni.createCanvasContext('canvas')
ctx.drawImage(res.path, 0, 0, that.cWidth, that.cHeight)
ctx.draw(false, setTimeout(() => {
uni.canvasToTempFilePath({
canvasId: 'canvas',
destWidth: that.cWidth,
destHeight: that.cHeight,
fileType: 'jpg',
quality: 0.4,
success: function(res1) {
callback && callback(res1.tempFilePath)
},
fail: function(res) {
console.log(res.errMsg)
}
})
}, 100))
},
})
},
recursionCompressH5(url, callback) {
let indexObj = this;
uni.getImageInfo({
src: url,
success(res) {
let canvasWidth = res.width;
let canvasHeight = res.height;
let img = new Image();
img.src = res.path;
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = canvasWidth / 2;
canvas.height = canvasHeight / 2;
ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
canvas.toBlob(function (fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc);
uni.getFileInfo({
filePath: imgSrc,
success:(resFileInfo) => {
if (resFileInfo.size > 1024 * 1024) {
indexObj.recursionCompressH5(imgSrc, callback);
return;
} else {
callback && callback(imgSrc)
}
},
});
});
}
});
},
upLoadImgs(path,type){
console.log(path);
uni.showLoading({
title:'上传中'
})
uni.uploadFile({
url:"https://wandianhuolian.ncltkj.com/"+this.$api.upLoad.upLoad,
filePath: path,
header:{
'Authorization' : "Bearer " + uni.getStorageSync('token'),
},
name:'upload',
success:resp=>{
uni.hideLoading()
if(resp.statusCode == 200){
const data = JSON.parse(resp.data)
console.log(data);
}else{
uni.showToast({
title:'上传失败',
icon:'none',
duration:1500
})
}
}
})
}
}