Categories
JavaScript Answers

How to compress an image via JavaScript in the browser?

Spread the love

Sometimes, we want to compress an image via JavaScript in the browser.

In this article, we’ll look at how to compress an image via JavaScript in the browser.

How to compress an image via JavaScript in the browser?

To compress an image via JavaScript in the browser, we can use the compressorjs library.

To install it, we run

npm i compressorjs

Then we write

import axios from "axios";
import Compressor from "compressorjs";

document.getElementById("file").addEventListener("change", (e) => {
  const file = e.target.files[0];

  if (!file) {
    return;
  }

  new Compressor(file, {
    quality: 0.6,
    async success(result) {
      const formData = new FormData();
      formData.append("file", result, result.name);
      await axios.post("/path/to/upload", formData);
      console.log("Upload success");
    },
    error(err) {
      console.log(err.message);
    },
  });
});

to select the file input with getElementById.

Then we call addEventListener to listen to the change event.

In the event listener, we get the first selected file with

const file = e.target.files[0];

Then we create a Compressor object with the selected file and then get the compressed file from the success method.

In success, we upload the result with axios.post.

Conclusion

To compress an image via JavaScript in the browser, we can use the compressorjs library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *