将图片导入到canvas画布中,利用画布重绘压缩图片,降低图片质量
//图片压缩
export function compress(fileObj, callback) {
const image = new Image()
image.src = URL.createObjectURL(fileObj)
image.onload = function() {
const that = this
// 默认按比例压缩
let w = that.width
let h = that.height
const scale = w / h
w = fileObj.width || w
h = fileObj.height || (w / scale)
let quality = 0.7 // 默认图片质量为0.7
// 生成canvas
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// 创建属性节点
const anw = document.createAttribute('width')
anw.nodeValue = w
const anh = document.createAttribute('height')
anh.nodeValue = h
canvas.setAttributeNode(anw)
canvas.setAttributeNode(anh)
ctx.drawImage(that, 0, 0, w, h)
// 图像质量
if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
quality = fileObj.quality
}
// quality值越小,所绘制出的图像越模糊
const data = canvas.toDataURL('image/jpeg', quality)
// 压缩完成执行回调
callback(data)
}
}
压缩方法调用
//上传图片------------------只有新增图片时才会触发
uploadPic(file) {
const imgSize = file.size / 1024 / 200;
const that = this;
if (imgSize > 1) {
this.dialogImageUrl = URL.createObjectURL(file.raw);
// 压缩图片
compress(file.raw, function (val) {
//调用图片上传接口,获取ecs图片文件名
that.uploadPicture(file.uid, val.split(",")[1],imgArrFiles);
});
} else {
//读取文件
let reader = new FileReader();
reader.readAsDataURL(file.raw);
reader.onload = function () {
// 读取文件base64
that.uploadPicture(file.uid, reader.result.split(",")[1]);
};
}
},
// 图片上传
async uploadPicture(imgId, picStr) {
let res = await post("//uploadPicture", {
picUrl: picStr,
});
if (res.code === "success") {
console.log("上传成功")
}
},