图片等比压缩是一种常见的需求,特别是在网页加载优化和存储空间节省方面。以下是一个使用JavaScript实现图片等比压缩的示例代码,并解释相关概念、优势、类型、应用场景以及可能遇到的问题和解决方法。
等比压缩:保持图片的原始宽高比不变,通过调整图片的尺寸来减小文件大小。
以下是一个使用JavaScript和HTML5 Canvas进行图片等比压缩的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Compression</title>
</head>
<body>
<input type="file" id="fileInput" accept="image/*">
<img id="preview" alt="Preview">
<script>
document.getElementById('fileInput').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 compressedImage = canvas.toDataURL('image/jpeg', 0.8); // 压缩质量为80%
document.getElementById('preview').src = compressedImage;
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
canvas.toDataURL
中的质量参数,通常在0到1之间。通过以上代码和解释,你应该能够实现图片的等比压缩,并理解其背后的原理和应用场景。
没有搜到相关的沙龙