beforeUpload(file) {
// 文件上传前钩子
var result = _g.checkUploadImg(file, this.rules);
if (result !== true) {
_g.message(result, "error");
return false;
}
const isJpgOrPng =
file.type === "image/jpeg" ||
file.type === "image/png" ||
file.type === "image/jpg"; //图片格式是否为png或jpg
const isLt5M = file.size / 1024 / 1024 < 5; //判断图片大小是否超过5MB
if (isJpgOrPng) {
if (!isLt5M) {
this.$message.error("文件过大!");
return false;
}
const _this = this;
return new Promise(resolve => {
const reader = new FileReader();
const image = new Image();
image.onload = async imageEvent => {
const originWidth = image.width;
const originHeight = image.height;
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
// 最大尺寸限制,可通过设置宽高来实现图片压缩程度
let maxWidth = 800,
maxHeight = 800;
// 目标尺寸
let targetWidth = originWidth,
targetHeight = originHeight;
// 图片尺寸超过800x800的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(
maxWidth * (originHeight / originWidth)
);
} else {
targetHeight = maxHeight;
targetWidth = Math.round(
maxHeight * (originWidth / originHeight)
);
}
}
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
context.fillRect(0, 0, canvas.width, canvas.height);
context.save();
context.drawImage(image, 0, 0, targetWidth, targetHeight);
try {
const res = await axios({
method: "post", // 请求方式
url: "/shrink", // 请求接口
baseURL: "", // 运维配置的请求地址
headers: {
Authorization:"" // 请求头参数,可以在登录后tiny上获取
},
data: file // 数据
});
let str = res.data.output.url.substring(22);
const res2 = await axios({
method: "get", // 请求方式
url: str, // 请求接口
baseURL: "", // 运维配置的请求地址
responseType: "arraybuffer"
});
let url =
"data:image/png;base64," +
btoa(
new Uint8Array(res2.data).reduce(
(data, byte) => data + String.fromCharCode(byte),
""
)
);
const blobData = _this.dataURItoBlob(url);
resolve(blobData);
} catch (error) {
resolve();
console.log(error);
}
};
reader.onload = e => {
image.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
return true;
},
vue+elementui调用tiny(熊猫压缩)接口进行图片压缩
于 2023-02-20 18:53:21 首次发布