在JavaScript中修改上传图片的大小通常涉及到以下几个步骤:
以下是一个简单的示例,展示如何使用JavaScript和Canvas API来调整上传图片的大小:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Resize Image</title>
</head>
<body>
<input type="file" id="imageUpload" accept="image/*">
<br>
<img id="preview" alt="Image Preview">
<script>
document.getElementById('imageUpload').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
const maxWidth = 800;
const maxHeight = 600;
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);
const resizedImage = canvas.toBlob(function(blob) {
const resizedUrl = URL.createObjectURL(blob);
document.getElementById('preview').src = resizedUrl;
}, 'image/jpeg', 0.8); // 质量设置为0.8
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
toBlob
方法的第三个参数来控制输出图片的质量。通过上述方法,可以在前端有效地调整上传图片的大小,同时保证良好的用户体验和性能。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云