在JavaScript中缩放图片通常涉及以下几个基础概念:
以下是一个使用Canvas API进行图片等比例缩放的示例代码:
function resizeImage(file, maxWidth, maxHeight, quality) {
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) => {
if (blob) {
resolve(blob);
} else {
reject(new Error('图片缩放失败'));
}
}, 'image/jpeg', quality);
};
img.onerror = () => {
reject(new Error('图片加载失败'));
};
});
}
// 使用示例
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
try {
const resizedImage = await resizeImage(file, 800, 600, 0.8);
const url = URL.createObjectURL(resizedImage);
const imgElement = document.createElement('img');
imgElement.src = url;
document.body.appendChild(imgElement);
} catch (error) {
console.error(error);
}
});
ctx.imageSmoothingEnabled = true;
)。URL.createObjectURL
后调用URL.revokeObjectURL
释放内存。通过以上方法和注意事项,可以在JavaScript中高效地实现图片缩放功能。
腾讯云存储知识小课堂
企业创新在线学堂
高校公开课
腾讯云存储知识小课堂
腾讯云存储知识小课堂
云+社区沙龙online [技术应变力]
腾讯云GAME-TECH游戏开发者技术沙龙
腾讯云智慧地产云端大讲堂
领取专属 10元无门槛券
手把手带您无忧上云