图片压缩画质
- 方法1:压缩图片--根据 宽 高 画质压缩图片
- 方法二:压缩图片--根据画质压缩图片
- 方法调用
方法1:压缩图片–根据 宽 高 画质压缩图片
compressUpload(file, config) {
let read = new FileReader();
read.readAsDataURL(file);
const fileName = file.name;
return new Promise((resolve, reject) => {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let _this = this;
read.onload = function (e) {
let img = new Image();
img.src = e.target.result;
img.onload = function () {
let w = this.width;
let h = this.height;
let scale = w / h;
w = config.width || config.height * scale || w;
h = config.height || config.width / scale || h;
w = config.maxWidth && w > config.maxWidth ? config.maxWidth : w;
h = config.maxHeight && h > config.maxHeight ? config.maxHeight : h;
w = Math.min(w, h * scale) || w;
h = Math.min(h, w / scale) || h;
let quality = 0.7;
let anw = document.createAttribute("width");
anw.nodeValue = w;
let anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(this, 0, 0, w, h);
if (config.quality && config.quality <= 1 && config.quality > 0) {
quality = config.quality;
}
let base64 = canvas.toDataURL("image/jpeg", quality);
resolve(base64);
canvas = null;
};
};
});
},
方法二:压缩图片–根据画质压缩图片
compressUpload(image, file, quality) {
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 base64 = canvas.toDataURL(file.type || "image/jpeg", quality);
return base64;
canvas = null;
},
方法调用
<el-upload
ref="upload"
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:before-upload="beforeUpload"
:auto-upload="false"
accept=".jpg,.png,.jpeg"
:on-change="handleChange"
>
<!-- <img v-if="imageUrl1" class="avatar-uploader-icon" :src="imageUrl1" alt="" /> -->
<i class="el-icon-plus avatar-uploader-icon"></i>
beforeUpload(file) {
console.log("压缩前:", file);
let _this = this;
const isIMG = file.type == "image/jpeg" || file.type == "image/png" || file.type == "image/jpg";
const isLt2M = file.size / 1024 / 1024 < 5;
if (!isIMG) {
this.$message.error("上传图片只能是 .jpg/.png/.jpeg 格式!");
}
if (!isLt2M) {
this.$message.error("上传文件大小不能超过 5MB!");
}
return new Promise((resolve, reject) => {
let isLt2M = file.size / 1024 / 1024 < 10;
if (!(isLt2M && isIMG)) {
reject();
}
let image = new Image(),
resultBlob = "";
image.src = URL.createObjectURL(file);
image.onload = () => {
resultBlob = _this.compressUpload(file, this.form);
resultBlob = _this.compressUpload(image, file, this.form.quality);
resolve(resultBlob);
};
image.onerror = () => {
reject();
};
});
},