帮我下一段简单的html压缩上传图片的代码
时间: 2023-12-23 08:02:44 浏览: 54
以下是一个简单的HTML上传图片的代码,同时对图片进行压缩:
```html
<!DOCTYPE html>
<html>
<head>
<title>上传并压缩图片</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" accept="image/*">
<br><br>
<button type="submit">上传并压缩图片</button>
</form>
<script>
const imageInput = document.getElementById('image');
imageInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => {
const img = new Image();
img.src = e.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const MAX_WIDTH = 800;
let scale = 1;
if (img.width > MAX_WIDTH) {
scale = MAX_WIDTH / img.width;
}
canvas.width = img.width * scale;
canvas.height = img.height * scale;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
const compressedFile = new File([blob], file.name, { type: file.type });
const formData = new FormData();
formData.append('image', compressedFile);
// 上传 formData 到服务器
}, file.type, 0.7);
};
};
});
</script>
</body>
</html>
```
这段代码使用了canvas对图片进行压缩,并将压缩后的图片转换为File对象,最后通过FormData上传至服务器。
阅读全文