后端要求前端上传图片时进行压缩,本文记录js和canvas来压缩图片,时间有点久,忘记原文的地址了
compressImg(file) {
const _that = this;
var fileSize = parseFloat(parseInt(file["size"]) / 1024 / 1024).toFixed(2);
var read = new FileReader();
read.readAsDataURL(file);
return new Promise(function(resolve) {
const type = file.type,
fileName = file.name;
read.onload = function(e) {
const img = new Image();
img.src = e.target.result;
img.onload = function() {
let w = this.width > 1440 ? 1400 : this.width,
h =
this.width > 1440
? 1440 * (this.height / this.width)
: this.height;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
let base64;
canvas.setAttribute("width", w);
canvas.setAttribute("height", h);
ctx.drawImage(this, 0, 0, w, h);
if (fileSize < 1) {
base64 = canvas.toDataURL(type, 1);
} else if (fileSize > 1 && fileSize < 2) {
base64 = canvas.toDataURL(type, 0.8);
} else {
base64 = canvas.toDataURL("image/jpeg", 0.2);
}
let f = _that.base64URLtoFile(base64, fileName);
resolve(f);
};
};
});
},