How to do image resizing client-side with JavaScript before upload to the server?

Sometimes, we want to do image resizing client-side with JavaScript before upload to the server.

In this article, we’ll look at how to do image resizing client-side with JavaScript before upload to the server.

How to do image resizing client-side with JavaScript before upload to the server?

To do image resizing client-side with JavaScript before upload to the server, we can use the compress.js package.

To install it, we run

npm i compress.js

Then we use it by writing

const compress = new Compress();

document.getElementById("select").onchange = async (evt) => {
  const files = [...evt.target.files];
  const data = await compress.compress(files, {
    size: 4,
    quality: 0.75,
    maxWidth: 1920,
    maxHeight: 1920,
    resize: true,
    rotate: false,
  });
  //...
};

to select the file input with

document.getElementById("select")

Then we set its onchange property to a function that runs when we select files.

In the function, we call compress.compress with the files array with the image files.

And we set the maxWidth and maxHeight and set resize to true to change the size of the images.

Then we get the resized image from the data array.

Conclusion

To do image resizing client-side with JavaScript before upload to the server, we can use the compress.js package.