Categories
JavaScript

Compress Images Before Uploading to a Server with the Compress.js Library

Spread the love

To save time uploading our images, we can compress them before uploading them.

We can do that easily with the Compress.js library.

In this article, we’ll look at how to use the Compress.js library to compress images before uploading.

Installation

The Compress.js library is available as a Node package.

This library is used on the client-side.

To install it, we run:

npm install compress.js --save

Compress Images

We can compress images easily whenever we select an image file.

To do that, we write:

<div>
  <input type='file' id='upload' />
</div>

Then write:

const Compress = require("compress.js");
const compress = new Compress();

compress
  .attach("#upload", {
    size: 4,
    quality: 0.75
  })
  .then((data) => {
    console.log(data);
  });

to watch the file input with ID upload for changes and compress the image that’s selected.

Then data parameter has an array of compressed images.

We can also select multiple images and compress them all at the same time.

For example, we can write:

<div>
  <input type='file' id='upload' multiple />
</div>

Then we write:

const Compress = require("compress.js");
const compress = new Compress();

compress
  .attach("#upload", {
    size: 4,
    quality: 0.75
  })
  .then((data) => {
    console.log(data);
  });

We can also add more configuration by writing:

const upload = document.getElementById("upload");
upload.addEventListener(
  "change",
  function (evt) {
    const files = [...evt.target.files];
    compress
      .compress(files, {
        size: 4,
        quality: 0.75,
        maxWidth: 1920,
        maxHeight: 1920,
        resize: true
      })
      .then((data) => {
        console.log(data);
      });
  },
  false
);

We listen to file input changes with the addEventListener method.

The size is the max size of the file in MB.

quality is the quality of the image with the max being 1.

maxWidth is the max-width of the output image.

maxHeight is the max height of the output image.

resize indicates whether we resize the image or not.

false in the 3rd argument disables capture mode.

File Upload

To do the file upload, we can use the fetch function by writing:

const upload = document.getElementById("upload");
upload.addEventListener(
  "change",
  function (evt) {
    const files = [...evt.target.files];
    compress
      .compress(files, {
        size: 4,
        quality: 0.75,
        maxWidth: 1920,
        maxHeight: 1920,
        resize: true
      })
      .then((imgData) => {
        const formData = new FormData();
        for (const { data, ext } of imgData) {
          const newFile = dataURIToBlob(data, ext);
          formData.append("image", newFile);
        }
        return fetch(
          "https://run.mocky.io/v3/c5189845-2a93-49aa-85c7-70bc64e8af90",
          {
            method: "POST",
            body: formData
          }
        );
      })
      .then((res) => res.text());
  },
  false
);

We compress the files the same way.

Then we append the images to the FormData instance, we created.

To do that, we convert the base64 images back to file objects first.

We did that with the dataURIToBlob method to convert the base64 string to an Uint8Array .

The mimeString is from the ext property of the resolved objects.

Then we loop through that and put and put the data into the Blob constructor.

And then we call fetch with it to send it to the server.

Conclusion

We can compress images before uploading them in a JavaScript browser app with the Compress.js 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 *