这里的<img>
标签是用来预览图片的:
<input id="upload" type="file" accept="image/*">
<img id="image" src="" alt="" />
读取上传文件:
let upload = document.querySelector('#upload');
let image = document.querySelector('#image');
let img = new Image();
let base64 = "";
upload.addEventListener('change', function (e) {
let file = e.target.files[0];
let reader = new FileReader();
reader.onload = function (e) {
let result = e.target.result;
img.src = result;
//压缩
img.onload = compress;
};
reader.readAsDataURL(file);
});
利用canvas
进行图片的压缩:
function compress() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
let width = img.width;
let height = img.height;
//如果图片大于四百万像素,计算压缩比并将大小压至400万以下
let ratio;
if ((ratio = width * height / 4000000) > 1) {
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
context.fillStyle = "#fff";
context.fillRect(0, 0, canvas.width, canvas.height);
context.drawImage(img, 0, 0, width, height);
base64 = canvas.toDataURL('image/jpeg', 0.1);
//图片预览
image.src = base64;
}
我们比较两张图片压缩前后的区别: