compressImg(file) {
console.log("compressImg============file",file)
let fileName = file.file.name;
// maxSize 是压缩的设置,设置图片的最大宽度和最大高度,等比缩放,level 质量,数值越小质量越低
let maxSize = {
width: 1000, height: 1000, level: 0.8 };
let _this = this;
let newFile = file.file;
let reader = new FileReader();
reader.readAsDataURL(newFile);
reader.onload = function(event) {
console.log("event.target.result",event);
let IMG = new Image();
IMG.src = event.target.result;
let imgWidth = 0,imgHeight = 0;
IMG.onload = function() {
let w = this.naturalWidth,
h = this.naturalHeight;
if (w > maxSize.width || h > maxSize.height) {
let multiple = Math.max(w / maxSize.width, h / maxSize.height);
imgWidth = w / multiple;
imgHeight = h / multiple;
let canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = imgWidth;
canvas.height = imgHeight;
ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
let base64 = canvas.toDataURL('image/jpeg', maxSize.level || 1);
_this.imgFile.file = _this.dataURLtoFile(base64, fileName);
} else {
_this.imgFile.file = file.file;
}
console.log("_this.formData1=====",_this.imgFile)
}
}
},
/**
* base64转文件
*/
dataURLtoFile(dataurl, filename) {
console.log("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);
}
console.log("dataURLtoFile==========return",new File([u8arr], filename, {
type: mime }));
return new File([u8arr], filename, {
type: mime });
},