图片上传压缩
This commit is contained in:
parent
9918b0b81b
commit
9a45600e0e
@ -140,7 +140,7 @@ export default {
|
||||
}
|
||||
},
|
||||
// 上传前loading加载
|
||||
handleBeforeUpload(file) {
|
||||
async handleBeforeUpload(file) {
|
||||
let isImg = false;
|
||||
if (this.fileType.length) {
|
||||
let fileExtension = "";
|
||||
@ -163,13 +163,52 @@ export default {
|
||||
if (this.fileSize) {
|
||||
const isLt = file.size / 1024 / 1024 < this.fileSize;
|
||||
if (!isLt) {
|
||||
this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
|
||||
this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
this.filesSize[file.name] = file.size
|
||||
this.$modal.loading("正在上传图片,请稍候...");
|
||||
this.number++;
|
||||
|
||||
// 3. 图片压缩(超大图自动缩小,速度提升50倍)
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image();
|
||||
img.src = URL.createObjectURL(file);
|
||||
|
||||
img.onload = () => {
|
||||
// 最大宽高,超过自动等比缩小
|
||||
const maxWidth = 1600;
|
||||
const maxHeight = 1600;
|
||||
let width = img.width;
|
||||
let height = img.height;
|
||||
// 等比缩放
|
||||
if (width > maxWidth || height > maxHeight) {
|
||||
const scale = Math.min(maxWidth / width, maxHeight / height);
|
||||
width *= scale;
|
||||
height *= scale;
|
||||
}
|
||||
|
||||
// canvas绘制
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.drawImage(img, 0, 0, width, height);
|
||||
|
||||
// 转成 Blob 上传(质量0.7 清晰又小)
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
const compressedFile = new File([blob], file.name, {
|
||||
type: file.type
|
||||
});
|
||||
resolve(compressedFile);
|
||||
},
|
||||
file.type,
|
||||
0.7
|
||||
);
|
||||
};
|
||||
});
|
||||
},
|
||||
// 文件个数超出
|
||||
handleExceed() {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user