export const pictureCompression = (file, callback) => {
const reader = new FileReader();
const img = new Image();
reader.onload = (e) => (img.src = e.target.result);
reader.readAsDataURL(file);
const canvas = document.createElement('canvas');
const canvasContext = canvas.getContext('2d');
img.onload = () => {
// 图片原始尺寸
let originWidth = img.width;
let originHeight = img.height;
// 最大尺寸限制
let maxWidth = 600;
let maxHeight = 600;
// 目标尺寸
let targetWidth = originWidth;
let targetHeight = originHeight;
// 图片尺寸超过400x400的限制
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;
// 清除画布
canvasContext.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
canvasContext.drawImage(img, 0, 0, targetWidth, targetHeight);
if (canvas.toBlob) {
// canvas转为blob并上传
canvas.toBlob(function(blob) {
callback(blob);
}, file.type || 'image/png');
} else {
callback(file);
}
};
};
export const pictureCompressionPromise = (file) => {
const reader = new FileReader();
const img = new Image();
reader.onload = (e) => (img.src = e.target.result);
reader.readAsDataURL(file);
const canvas = document.createElement('canvas');
const canvasContext = canvas.getContext('2d');
return new Promise((resolve) => {
img.onload = () => {
// 图片原始尺寸
let originWidth = img.width;
let originHeight = img.height;
// 最大尺寸限制
let maxWidth = 600;
let maxHeight = 600;
// 目标尺寸
let targetWidth = originWidth;
let targetHeight = originHeight;
// 图片尺寸超过400x400的限制
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;
// 清除画布
canvasContext.clearRect(0, 0, targetWidth, targetHeight);
// 图片压缩
canvasContext.drawImage(img, 0, 0, targetWidth, targetHeight);
if (canvas.toBlob) {
// canvas转为blob并上传
canvas.toBlob(function(blob) {
resolve(blob);
}, file.type || 'image/png');
} else {
resolve(file);
}
};
});
};