Image Compressor Tool
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f7f9fc;
color: #333;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
text-align: center;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
max-width: 400px;
width: 100%;
}
h1 {
color: #4caf50;
}
.preview {
margin: 15px 0;
}
img {
max-width: 100%;
height: auto;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.compression-settings {
margin: 20px 0;
}
input[type="file"] {
margin-bottom: 15px;
}
input[type="range"] {
width: 100%;
}
button {
background-color: #4caf50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #45a049;
}
a {
display: inline-block;
margin-top: 20px;
background-color: #2196f3;
color: white;
padding: 10px 20px;
border-radius: 5px;
text-decoration: none;
transition: background-color 0.3s ease;
}
a:hover {
background-color: #1976d2;
}
@media (max-width: 768px) {
.container {
padding: 15px;
}
button, a {
padding: 8px 15px;
}
}
const imageInput = document.getElementById('imageInput');
const previewImg = document.getElementById('previewImg');
const qualityRange = document.getElementById('qualityRange');
const qualityValue = document.getElementById('qualityValue');
const compressBtn = document.getElementById('compressBtn');
const downloadLink = document.getElementById('downloadLink');
let imageFile;
// Update quality value display
qualityRange.addEventListener('input', () => {
qualityValue.textContent = qualityRange.value;
});
// Display image preview when a file is selected
imageInput.addEventListener('change', (event) => {
imageFile = event.target.files[0];
if (imageFile) {
const reader = new FileReader();
reader.onload = (e) => {
previewImg.src = e.target.result;
previewImg.style.display = 'block';
};
reader.readAsDataURL(imageFile);
}
});
// Compress image on button click
compressBtn.addEventListener('click', async () => {
if (!imageFile) {
alert('Please upload an image first.');
return;
}
const options = {
maxSizeMB: 1,
maxWidthOrHeight: 1920,
useWebWorker: true,
initialQuality: parseFloat(qualityRange.value),
};
try {
const compressedFile = await imageCompression(imageFile, options);
const compressedBlobUrl = URL.createObjectURL(compressedFile);
// Display compressed image for download
downloadLink.href = compressedBlobUrl;
downloadLink.style.display = 'inline-block';
downloadLink.textContent = 'Download Compressed Image';
} catch (error) {
console.error('Error compressing the image:', error);
}
});
No comments:
Post a Comment