JavaScript 压缩图片并保持固定比例通常涉及以下几个基础概念:
以下是一个简单的示例,展示如何使用 JavaScript 和 Canvas API 来压缩图片并保持其固定比例:
function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = () => {
const canvas = document.createElement('canvas');
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;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
resolve(blob);
}, 'image/jpeg', quality);
};
img.onerror = reject;
});
}
// 使用示例
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async (event) => {
const file = event.target.files[0];
try {
const compressedImage = await compressImage(file, 800, 600, 0.8);
console.log('Compressed image:', compressedImage);
} catch (error) {
console.error('Error compressing image:', error);
}
});maxWidth、maxHeight 和 quality 参数。canvas.toBlob 方法。可以使用 polyfill 或者回退到 canvas.toDataURL 方法。toBlob 的浏览器,可以使用 toDataURL 并手动转换成 Blob。通过上述方法和代码示例,可以在 JavaScript 中实现图片的压缩并保持固定比例,同时考虑到性能和兼容性问题。
没有搜到相关的沙龙