图片等比例缩放是指在调整图片尺寸时,保持图片的宽高比不变,以避免图片变形。这通常涉及到计算新的宽度和高度,使得它们与原始宽高比相匹配。
以下是一个使用JavaScript实现图片等比例缩放的示例代码:
function resizeImage(file, maxWidth, maxHeight) {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = () => {
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
resolve(blob);
}, file.type);
};
img.onerror = reject;
});
}
// 使用示例
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (event) => {
const file = event.target.files[0];
resizeImage(file, 800, 600).then((resizedImage) => {
console.log('Resized image:', resizedImage);
}).catch((error) => {
console.error('Error resizing image:', error);
});
});
img.onerror
回调,处理加载失败的情况。canvas.toBlob
方法中设置合适的图像质量参数,例如:canvas.toBlob
方法中设置合适的图像质量参数,例如:通过以上方法和代码示例,可以有效实现图片的等比例缩放,并解决常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云