我试了很多方法最后
都很拉跨
最后…
直接调用这个addImg()
// 压缩图片02
photoCompress(file,objdiv) {
var ready = new FileReader();
ready.readAsDataURL(file);
const _this = this;
ready.onload = function() {
var fileResult = this.result;
_this.canvasDataURL(fileResult,objdiv)
}
},canvasDataURL(path,callback) {
var img = new Image();
img.src = path;
var objCompressed = {}
img.onload = function() {
var that = this;
//默认压缩后图片规格
var quality = 0.7;
var w = that.width;
var h = that.height;
var scale = w / h;
//实际要求
w = objCompressed.width || w;
h = objCompressed.height || (w / scale);
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that,0,w,h);
var base64 = canvas.toDataURL('image/jpeg',quality);
// 回调函数返回base64的值
callback(base64);
}
},dataURLtoFile(dataurl,filename) {
var arr = dataurl.split(","),mime = arr[0].match(/:(.*?);/)[1],bstr = atob(arr[1]),n = bstr.length,u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr],filename,{ type: mime });
},// 压缩图片02
addImg(){
uni.chooseImage({
success:(res) =>{
let i = 0
// 压缩上传02
for (let file of res.tempFiles) {
// this.multipartUpload(i,file)
const imgSize = res.tempFiles[i] && res.tempFiles[i].size ? res.tempFiles[i].size : 0;
const imgName = res.tempFiles[i]&&res.tempFiles[i].name?res.tempFiles[i].name:'';
// console.log(imgSize,file)
this.photoCompress(res.tempFiles[i],(base64Codes) => {
var fl = this.dataURLtoFile(base64Codes,imgName)
// console.log(fl.size,fl,"压缩后的文件")
})
i++
}
// 压缩上传02
}
});
},
转发于https://blog.csdn.net/baidu_41604826/article/details/111224603
在此表达感谢