Compress the image on the client side before uploading using JavaScript.
Optimizing images is always a good idea. It reduces the total amount of data being transferred over the network and memory consumption. What, if we could compress the image before uploading it to the server? It is possible. Let’s dive into that.
Introduction
Image optimization is an important strategy for improving performance. Compressing an image before uploading gives an opportunity to reduce its file size without losing the quality before uploading to the server.
Should I compress images before uploading?
There are several benefits:
- Faster uploading and downloading data.
- Reducing memory consumption.
- Saves the space on the server.
How to use JavaScript to compress the image before upload
To compress an image via JavaScript in the browser we’ll use Canvas API for that purpose. What is needed is to attach the event handler for the event type change
and HTML element input type file
, then process the image using canvas
and the canvas.toBlob
method.
You can automate that process and use our npm package @sitelintcode/optimize-image-on-the-client-side with documentation on how to install and use it.
Here is the basic code if you want to use it straight on your site and get the package from jsdelivr.com (free, fast, and reliable CDN for JS and open source).
optimize-image-on-the-client-side.js
installation code, specific version<script src="https://cdn.jsdelivr.net/npm/@sitelintcode/optimize-image-on-the-client-side@0.0.23/dist/optimize-image-on-the-client-side.js"></script>
<script>
(function() {
const optimizeImage = new window.sitelint.OptimizeImage();
optimizeImage.install();
}())
</script>
Worth to mention that jsdelivr.com suggest: Omit the
version
completely or use latest
to load the latest one (not recommended for production usage):
optimize-image-on-the-client-side.js
jsdelivr installation code, latest versionhttps://cdn.jsdelivr.net/npm/@sitelintcode/optimize-image-on-the-client-side@latest/dist/optimize-image-on-the-client-side.js
Full code for image compression is available on GitHub.
Limitations
There are several limitations:
- Browsers are required to support
image/png
, but many will support additional formats includingimage/jpeg
, andimage/webp
. - The event type
change
attached to theinput type file
may not be executed correctly when there are multiple event handlers. - Founded issue or have a suggestion? Visit optimize-image-on-the-client-side on GitHub.
Workable example
There is nothing better than a workable solution. See the image compression on the client-side example.
Comments