vue用cavans图片压缩并上传
陈杰2年前 (2020-11-04)VUE1177
//vue压缩图片上传
yasuo() {
let that = this
let file = that.imgUrls
uni.getImageInfo({
src: file.path,
success: function(res) {
let canvasWidth = res.width //图片原始长宽
let canvasHeight = res.height;
let base = canvasWidth / canvasHeight;
if (canvasWidth > 500) {
canvasWidth = 500;
canvasHeight = Math.floor(canvasWidth / base);
}
let img = new Image();
img.src = file.path; // 要压缩的图片
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// 将图片画到canvas上面 使用Canvas压缩
ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
canvas.toBlob(function(fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc); //原生JS生成文件路径
uni.downloadFile({
url: imgSrc, //仅为示例,并非真实的资源
success: (resFilePath) => {
console.log(resFilePath);
if (resFilePath.statusCode === 200) {
//resolve(resFilePath);
that.imageYasuo = resFilePath
}
}
});
});
},
})
}