在JavaScript中实现图片压缩上传主要涉及到图像处理和文件上传两个环节。以下是相关的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方案:
// HTML部分
<input type="file" id="upload" accept="image/*">
<canvas id="canvas" style="display:none;"></canvas>
// JavaScript部分
document.getElementById('upload').addEventListener('change', function(event) {
const file = event.target.files[0];
if (!file) return;
const img = new Image();
const reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
};
img.onload = function() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置压缩后的尺寸
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;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
// 导出压缩后的图片数据
const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.8); // 0.8为压缩质量
// 上传图片(示例使用Fetch API)
fetch('/upload', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ image: compressedDataUrl })
}).then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
};
reader.readAsDataURL(file);
});
通过以上步骤和注意事项,可以实现有效的图片压缩上传功能。
领取专属 10元无门槛券
手把手带您无忧上云