Mb to KB Image Compressor ToolMB To KB Image Compressor
Compressed Image
`;
compressButton.style.display = "block";
} else {
alert("Please upload an image file.");
}
}
};const compressImage = () => {
if (selectedFile) {
const desiredSize = parseInt(desiredSizeInput.value, 10);
const sizeUnit = sizeUnitSelect.value;if (isNaN(desiredSize) || desiredSize <= 0) {
alert("Please enter a valid size.");
return;
}const desiredBytes = sizeUnit === "KB" ? desiredSize * 1024 : desiredSize * 1024 * 1024;const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
let quality = 0.7; // initial guess for quality
let compressedDataUrl;do {
compressedDataUrl = canvas.toDataURL('image/jpeg', quality);
quality -= 0.05;
} while (compressedDataUrl.length > desiredBytes && quality > 0);compressedPreview.innerHTML = `
`;
downloadButton.style.display = "block";
downloadButton.onclick = () => {
const link = document.createElement("a");
link.href = compressedDataUrl;
link.download = "compressed-image.jpg";
link.click();
};
};
};
reader.readAsDataURL(selectedFile);
} else {
alert("No image selected.");
}
};uploadArea.addEventListener("dragover", (event) => {
event.preventDefault();
uploadArea.classList.add("dragging");
});uploadArea.addEventListener("dragleave", () => {
uploadArea.classList.remove("dragging");
});uploadArea.addEventListener("drop", (event) => {
event.preventDefault();
uploadArea.classList.remove("dragging");
handleFiles(event.dataTransfer.files);
});uploadArea.addEventListener("click", () => {
fileInput.click();
});fileSelect.addEventListener("click", () => {
fileInput.click();
});fileInput.addEventListener("change", (event) => {
handleFiles(event.target.files);
});compressButton.addEventListener("click", compressImage);
});