Image Compression using JavaScript in Retool

Published On: 24 June 2022.By .
  • General

Large image takes more space and time to load and thus needs to be compressed . The biggest trade-off in image compressing is depletion of image quality so a perfect compression is where image quality is acceptable and as well as its size is also considerably reduced . Compression can be of two type lossy and lossless , in lossless the image size is not compressed much but image quality is well preserved , counter to this in lossy compression the image size is compressed significantly but image quality is depleted and this loss is irreversible one can not get original image back from the resultant image . Earlier JPEG (Joint Photographic Experts Group) was used for lossy image compression but nowadays JPEG-2000 is used which provides support for both lossy and lossless compression .

Now let’s see how we can compress image using JavaScript in Retool :

This will be a lossy compression , and we will be using Canvas  to achieve the desired output .

Aim : To compress image before uploading it to any cloud server .

Uploading image on retool

-> Once image is uploaded on Retool we are fetching its details and processing it .

->After loading the image in JavaScript we  can compress its size in 2 ways , 1 either by reducing its size (height and width) or reducing pixels density

For reducing its height and width :

if you want to conserve original height and width then we can skip this part of code .

->To reduce quality without compromising with its height and width :

 

->Complete code for compressing image without changing its width and height :

Results :

Original Image :


Original Image

Size : 130.9 kB

Compressed Image  :

Size : 109.4 kB                                                          Quality : 0.8 (80% of original image…)

Compressed Image :

Size : 41.6 kB                                                             Quality : 0.3 (30% of original image…)

 

Related content

That’s all for this blog