<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片压缩</title>
</head>
<body>
<input type="file" name="file" id="file">
</body>
<script>
const input = document.getElementById('file');
input.onchange = e => {
const fileReader = new FileReader();
if (e.target.files && e.target.files[0]);
const file = e.target.files[0];
console.log(
`name:${file.name}\n`,
`type:${file.type}\n`,
`size:${file.size}\n`,
)
// 把图片读成dataURL
fileReader.readAsDataURL(e.target.files[0]);
fileReader.onload = fileEvent => {
if (fileEvent && fileEvent.target && fileEvent.target.result) {
const img = new Image();
img.src = fileEvent.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 压缩有2中方式:
// 第一种只支持image/webp和image/jpeg格式,
// 将canvas的宽高设置成和原图一样,通过toBlob(cb,type,quality)的quality参数压缩;
// 第二种就是改变图片的宽和高.
const quality = 0.7;
canvas.width = quality * img.width;
canvas.height = quality * img.height;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height) // 将图片绘制在画板上
canvas.toBlob(blob => {
console.log(`new file size: ${blob.size}`)
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
a.href = url;
a.download = `${quality}quality-${file.name}`;
a.click();
window.URL.revokeObjectURL(url);
})
}
}
}
}
</script>
</html>
前端实现图片压缩
最新推荐文章于 2024-06-03 16:48:54 发布