Skip to content

Commit 3cec8f8

Browse files
authored
Create script.js
1 parent 5935479 commit 3cec8f8

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

script.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
function humanFileSize(size) {
2+
let i = Math.floor(Math.log(size) / Math.log(1024));
3+
return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB'][i];
4+
}
5+
6+
document.getElementById('imageInput').addEventListener('change', function (event) {
7+
const file = event.target.files[0];
8+
if (!file) return;
9+
10+
document.getElementById('fileInfo').innerHTML = `Original Size: ${humanFileSize(file.size)}`;
11+
12+
new Compressor(file, {
13+
quality: 0.6,
14+
success(result) {
15+
const compressedBlob = result;
16+
document.getElementById('fileInfo').innerHTML += `<br>Compressed Size: ${humanFileSize(compressedBlob.size)}`;
17+
18+
const downloadBtn = document.getElementById('downloadBtn');
19+
const url = URL.createObjectURL(compressedBlob);
20+
downloadBtn.style.display = 'inline-block';
21+
downloadBtn.onclick = function() {
22+
const a = document.createElement('a');
23+
a.href = url;
24+
a.download = 'compressed-image.jpg';
25+
document.body.appendChild(a);
26+
a.click();
27+
document.body.removeChild(a);
28+
};
29+
},
30+
error(err) {
31+
console.error(err.message);
32+
},
33+
});
34+
});

0 commit comments

Comments
 (0)