private getBase64(img: File, callback: (img: string) => void): void {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result!.toString()));
reader.readAsDataURL(img);
}
compressImg (file) {
if (['image/png','image/jpeg','image/jpg'].includes(file.type)) {
let _this = this;
this.getBase64(file, (src) => {
let img = new Image();
img.src = src;
img.onload = () => {
let originWidth = img.width;
let originHeight = img.height;
// 目标尺寸
let targetWidth = originWidth, targetHeight = originHeight;
let maxWidth = 'xxxx';
let maxHeight = 'xxx;
if (!maxWidth && !maxHeight) {
maxWidth = MAX_WIDTH;
maxHeight = MAX_HEIGHT;
}
if (originWidth > maxWidth || originHeight > maxHeight) {
if ((maxWidth && maxHeight) && (originWidth / originHeight > maxWidth / maxHeight) || maxWidth) {
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
// 新建画布
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
context.drawImage(img, 0, 0, targetWidth, targetHeight);
canvas.toBlob((blob) => {
let formData = new FormData();
formData.append('file', blob, file.name);
//请求数据
})
}
});
} else {
console.log('error', '文件格式不正确');
}
}
网友评论