beforeUpload(file) {
let _this = this;
return new Promise((resolve, reject) => {
// 判定图片大小是否小于10MB
//let isLt10M = file.size / 1024 / 1024 < 10;
//if (!isLt10M) {
//不管是不是小于10MB都会压缩
let image = new Image(),
resultBlob = "";
image.src = URL.createObjectURL(file);
image.onload = () => {
// 调用方法获取blob格式
resultBlob = _this.compressUpload(image, file);
resolve(resultBlob);
};
image.onerror = () => {
reject();
};
// }
});
},
/* 图片压缩方法-canvas压缩 */
compressUpload(image, file) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let { width } = image,
{ height } = image;
canvas.width = width;
canvas.height = height;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0, width, height);
// 进行压缩
let compressData = canvas.toDataURL(file.type || "image/jpeg", 0.5);
// 压缩后调用方法进行base64转Blob
let blobImg = this.dataURItoBlob(compressData);
return blobImg;
},
/* base64转Blob对象 */
dataURItoBlob(data) {
let byteString;
if (data.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(data.split(",")[1]);
} else {
byteString = unescape(data.split(",")[1]);
}
let mimeString = data
.split(",")[0]
.split(":")[1]
.split(";")[0];
let ia = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i += 1) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString });
},