前端图片压缩主要利用 HTML5 中的 Canvas 对象来处理图片。用户上传的图片先在客户端进行压缩,然后再上传到服务器。这种方法可以减少服务器的负担和节省带宽。
步骤如下:
- 用户选择图片后,在前端使用 JavaScript 将图片绘制到 Canvas 元素上。
- 控制 Canvas 的尺寸,从而改变图片的分辨率或质量。
- 将 Canvas 上的内容转换为压缩后的图片格式。
- 最后将压缩后的图片上传到服务器。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.img-box {
border: 1px solid red;
}
</style>
</head>
<body>
<input type="file" accept="image/*" id="file-input">
<div class="img-box"></div>
<script>
// 获取用户上传的图片文件
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', function () {
const file = fileInput.files[0];
// console.log('file的值', file);
// 创建一个新的图片对象
const img = new Image();
// 添加加载完成的事件处理程序
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 控制图片尺寸
const maxWidth = 800;
const maxHeight = 600;
let width = img.width;
let height = img.height;
console.log('看看这里会打印东西么', width, height);
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
// console.log('看看这里会打印东西么', width, height);
canvas.width = width;
canvas.height = height;
// 在Canvas上绘制压缩后的图片
ctx.drawImage(img, 0, 0, width, height);
// 将Canvas上的内容导出为压缩后的Blob对象
canvas.toBlob((blob) => {
// 将Blob对象上传到服务器或其他操作
// 这里假设有一个上传图片的接口uploadImageToServer,将Blob对象上传到服务器
// const formData = new FormData();
// formData.append('image', blob, 'compressed_image.jpg');
// fetch('http://example.com/uploadImageToServer', {
// method: 'POST',
// body: formData
// })
// .then(response => {
// // 处理服务器响应
// })
// .catch(error => {
// console.error('Error uploading image to server:', error);
// });
}, 'image/jpeg', 0.3); // 设置压缩质量
};
// 读取用户上传的文件并将其作为图片源加载
const reader = new FileReader();
// 以 Data URL 的形式读取该文件的内容,然后触发 reader.onload 事件
reader.readAsDataURL(file);
reader.onload = function (e) {
img.src = e.target.result;
// clientWidth 返回的是元素的可见宽度,包括 padding,但不包括 border、margin 和滚动条。
// naturalWidth 返回的是图片的原始宽度,对于其他元素返回 0。
// img.width = img.naturalWidth * 0.3
// img.height = img.naturalHeight * 0.3
// 如果需要显示上传的图片,可以将其添加到页面中
const imgBox = document.getElementsByClassName('img-box')[0]
imgBox.appendChild(img);
};
});
</script>
</body>
</html>