-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
49 lines (42 loc) · 1.92 KB
/
script.js
File metadata and controls
49 lines (42 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const upload = document.getElementById("upload");
const original = document.getElementById("original");
const compressed = document.getElementById("compressed");
const originalInfo = document.getElementById("original-info");
const compressedInfo = document.getElementById("compressed-info");
const download = document.getElementById("download");
upload.addEventListener("change", (e) => {
const file = e.target.files[0];
if (!file) return;
// Display original
const originalURL = URL.createObjectURL(file);
original.src = originalURL;
originalInfo.textContent = `Original size: ${(file.size / 1024).toFixed(2)} KB`;
// Compress image using canvas
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const img = new Image();
img.src = event.target.result;
img.onload = function () {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Resize if needed (optional)
const maxWidth = 800; // Limit width for web
const scale = Math.min(1, maxWidth / img.width);
canvas.width = img.width * scale;
canvas.height = img.height * scale;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Compress (0.7 = 70% quality)
const compressedData = canvas.toDataURL("image/jpeg", 0.7);
compressed.src = compressedData;
// Convert to Blob to show compressed size
fetch(compressedData)
.then((res) => res.blob())
.then((blob) => {
compressedInfo.textContent = `Compressed size: ${(blob.size / 1024).toFixed(2)} KB`;
download.href = compressedData;
download.style.display = "inline-block";
});
};
};
});