Image Compression in ReactJs

Matheswaaran
Frontend Weekly
Published in
2 min readMar 16, 2021

--

Designed By Naren

While uploading the images to the block storage (or) S3 storage, the full images when captured through the phone (Pixel 3 or others) camera, has a size up to 3 MB. This consumes most of our time while uploading. So, I started looking into lossless compression techniques for images on the client-side.

I came across an amazing image compression package for Javascript called compressorjs.

We can resize, compress and convert the images based on our requirements.

To compress your images follow these three simple steps:

  • Install the package using npm/yarn
  • Add the particular code block to your project
  • Be Amazed!

Install the package using npm/yarn

To install the package, type one of the following commands based on your package manager

For npm:

npm install compressorjs

For Yarn:

yarn add compressorjs

Add the particular code block to your project

Add the code to your component before uploading. This code compresses the images to 80% of their original quality. We can use any percentage of compressing we need.

new Compressor(image, {      
quality: 0.8,
success: (compressedResult) => {
// compressedResult has the compressed file.
// Use the compressed file to upload the images to your server.
setCompressedFile(res)
},
});

The full example of how this code can be used in an upload component using ReactJs.

Be Amazed!

Horray! Once the magic happens, see the size of the image, the captured file of 2.8 MB is compressed to a 500 KB file.

To know more, visit their website here.

Say Hi, It’s free at @matheswaaran_S or https://matheswaaran.com

--

--