This JavaScript code helps you to compress image size before upload to server. It calculates and displays the original image size in MB when you choose an image. Then, it displays the image, compresses it into WebP format, and reveals the new compressed size in KB. This code is handy for making your web pages load faster by reducing image sizes before uploading them.
How to Compress Image Size Before Upload using JavaScript
1. Include the following HTML structure in your webpage. This code assumes you have an input field for selecting an image, a display area for the image before compression, and a display area for the image after compression.
<input type="file" name="upload-image" id="upload-image" required /> <h2> Before </h2> <p name="before-compression"></p> <img src="" class="before" style="display:none;"/> <canvas style="display: none;"></canvas> <h2> After </h2> <p name="after-compression"></p> <img src="" class="after" style="display:none;"/>
2. You can customize the CSS styles to match your website’s design, but the following code includes basic styling for the elements. Adjust it as needed.
#upload-image{ display: block; } .before, .after{ max-width: 640px; }
3. Copy and paste the JavaScript code into your webpage. This code handles the image compression process.
const ReadAndCompress = (e) => { const size = `Before Compression: ${(e.target.files[0].size/(1000*1024)).toFixed(2)} MB`; document.querySelector("p[name=before-compression]").innerHTML = size; const reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader.onload = event => { const img = document.querySelector("img.before"); img.src = event.target.result; img.style = "display: block"; img.onload = () => { const width = img.width; const height = img.height; const elem = document.querySelector('canvas'); elem.width = width; elem.height = height; const ctx = elem.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); const webp = ctx.canvas.toDataURL("image/webp", 0.5); const imgAfter = document.querySelector("img.after"); imgAfter.src = webp; imgAfter.style = "display: block"; const head = 'data:image/webp;base64,'; const imgFileSize = (Math.round((webp.length - head.length)*3/4) / (1000)).toFixed(2); document.querySelector("p[name=after-compression]").innerHTML = `After Compression: ${imgFileSize} KB`; }, reader.onerror = error => console.error(error); } } document.querySelector("input[name=upload-image]") .addEventListener("change", (event) => ReadAndCompress(event))
4. To upload the compressed image that is shown as output, you can modify the provided code by adding a function to send the compressed image to your server or a cloud storage service. Here’s a general outline of how you can do it:
<input type="file" name="upload-compressed-image" id="upload-compressed-image" required /> <button id="upload-button">Upload Compressed Image</button>
5. Add an event listener to the new upload button or form to trigger the upload process. You can use the Fetch API or any other method to send the compressed image to your server.
document.querySelector("#upload-button").addEventListener("click", () => { const compressedImage = document.querySelector("img.after").src; uploadCompressedImage(compressedImage); }); function uploadCompressedImage(compressedImage) { // Use the Fetch API or another method to send 'compressedImage' to your server. // You may need to handle server-side processing and storage of the uploaded image. }
Remember that the server-side handling part will depend on your backend technology stack. The code provided here outlines the client-side modifications to initiate the upload process.
That’s all! hopefully, you have successfully created a feature to compress Image size Before Upload. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.