JavaScript Image Compressor

HTML:
<input type="file" id="file-input">
<button id="compress-btn">Compress Image</button>
<img id="image-preview" src="" alt="Preview">
CSS:
#image-preview { max-width: 500px; max-height: 500px; }
JavaScript:
const fileInput = document.getElementById('file-input'); const compressBtn = document.getElementById('compress-btn'); const imagePreview = document.getElementById('image-preview');
fileInput.addEventListener('change', function() { const file = fileInput.files\[0\]; const reader = new FileReader();
reader.onload = function() { imagePreview.src = reader.result; }
reader.readAsDataURL(file); });
compressBtn.addEventListener('click', function() { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image();
img.onload = function() { const width = img.width; const height = img.height; const ratio = width / height; let max = Math.max(width, height);
if (max > 500) { max = 500; }
canvas.width = max \* ratio; canvas.height = max;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const compressedImage = canvas.toDataURL('image/jpeg', 0.5);
imagePreview.src = compressedImage; }
img.src = imagePreview.src; });
This code creates an input field for uploading an image, a button for compressing the image, and an image tag for previewing the uploaded image and the compressed image. When an image is uploaded, it is displayed in the preview. When the "Compress Image" button is clicked, the code creates a canvas element and draws the image onto it with a maximum size of 500x500 pixels. The compressed image is then displayed in the preview. The compression quality is set to 0.5, but you can adjust this value to suit your needs.
Adding more Features
- Allow the user to select the compression quality: We can add a range input field to allow the user to select the compression quality they want. The range input field can be added to the HTML code as follows:
<input type="range" id="quality-range" min="0.1" max="1" step="0.1" value="0.5">
In the JavaScript code, we can get the value of the range input field and pass it as the second parameter to the toDataURL method. The updated code would be as follows:
const qualityRange = document.getElementById('quality-range'); const qualityLabel = document.getElementById('quality-label');
qualityRange.addEventListener('input', function() { qualityLabel.innerText = qualityRange.value; });
// Inside the compressBtn click event listener const quality = parseFloat(qualityRange.value); const compressedImage = canvas.toDataURL('image/jpeg', quality);
Here, we are also adding an event listener to the range input field to update the label showing the current quality value.
- Add a download button to download the compressed image: We can add a download button to allow the user to download the compressed image. We can create a link element and set its
hrefattribute to thedataURLof the compressed image, and set the download attribute to the filename. The updated HTML code would be as follows:
<input type="file" id="file-input">
<button id="compress-btn">Compress Image</button>
<label for="quality-range" id="quality-label">0.5</label>
<input type="range" id="quality-range" min="0.1" max="1" step="0.1" value="0.5">
<a id="download-link" download="compressed-image.jpg">Download Compressed Image</a>
<img id="image-preview" src="" alt="Preview">
In the JavaScript code, we can add a click event listener to the download button, and set the href attribute of the link to the compressed image dataURL. The updated code would be as follows:
const downloadLink = document.getElementById('download-link');
downloadLink.addEventListener('click', function() { downloadLink.href = imagePreview.src; }); Add error handling for invalid file types: We can add error handling to prevent the user from uploading invalid file types, such as non-image files or files that are too large. We can check the file type and size before displaying the preview. The updated JavaScript code would be as follows: javascript Copy code fileInput.addEventListener('change', function() { const file = fileInput.files\[0\];
if (!file.type.startsWith('image/')) { alert('Please upload an image file.'); return; }
if (file.size > 5000000) { alert('Please upload an image smaller than 5MB.'); return; }
const reader = new FileReader();
reader.onload = function() { imagePreview.src = reader.result; }
reader.readAsDataURL(file); });
Here, we are checking the type and size properties of the file object, and displaying an alert message if they are not valid.
These are just a few examples of additional features that can be added to the image compressor. Depending on your requirements, you can add more features such as resizing options, image filters, etc.
