Image Compressor Tool
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 0 auto;
text-align: center;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
h1 {
color: #333;
}
h2 {
margin-top: 20px;
color: #333;
}
#fileInput {
display: none;
}
.output {
margin-top: 20px;
}
img {
max-width: 100%;
height: auto;
}
a {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: #fff;
text-decoration: none;
border-radius: 5px;
margin-top: 10px;
}
a:hover {
background-color: #0056b3;
}
const fileInput = document.getElementById('fileInput');
const compressedImage = document.getElementById('compressedImage');
const downloadLink = document.getElementById('downloadLink');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.src = e.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Resize the image to a desired width (e.g., 300 pixels)
const maxWidth = 300;
const scale = maxWidth / img.width;
canvas.width = maxWidth;
canvas.height = img.height * scale;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Convert the canvas to a data URL and set it as the compressed image source
const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.7);
compressedImage.src = compressedDataUrl;
// Enable download link with compressed image
downloadLink.href = compressedDataUrl;
downloadLink.style.display = 'block';
};
};
reader.readAsDataURL(file);
}
});
No comments:
Post a Comment