Build an Image Compressor using React


Build an Image Compressor using React
Build an Image Compressor using React

Images draw attention, trigger emotions, and improve the user experience of your website. Image compression involves the reduction of the size of your image so that it takes less space on the hard drive and for better search engine optimization when it comes to websites e.g., 2MB to 440kbs. The image still retains its physical properties. We are going to use React to compress our images.

 

  • React.js basic skills
  • Basic knowledge of HTML
  • Knowledge of Javascript
  • Some knowledge of Bootstrap

 

Features

  • You can use this module to compress jpeg, png, webp, and bmp images by reducing resolution or storage size before uploading to the application server to save bandwidth.
  • Multi-thread (web worker) non-blocking compression is supported through options.

 

Demo / Example

open https://rengga.dev/demo/react-image-compressor/

 

Usage

<input type="file" accept="image/*" onchange="handleImageUpload(event);">

async await syntax:

async function handleImageUpload(event) {

  const imageFile = event.target.files[0];
  console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
  console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);

  const options = {
    maxSizeMB: 1,
    maxWidthOrHeight: 1920,
    useWebWorker: true,
  }
  try {
    const compressedFile = await imageCompression(imageFile, options);
    console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
    console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB

    await uploadToServer(compressedFile); // write your own logic
  } catch (error) {
    console.log(error);
  }

}

Promise.then().catch() syntax:

function handleImageUpload(event) {

  var imageFile = event.target.files[0];
  console.log('originalFile instanceof Blob', imageFile instanceof Blob); // true
  console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);

  var options = {
    maxSizeMB: 1,
    maxWidthOrHeight: 1920,
    useWebWorker: true
  }
  imageCompression(imageFile, options)
    .then(function (compressedFile) {
      console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
      console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB

      return uploadToServer(compressedFile); // write your own logic
    })
    .catch(function (error) {
      console.log(error.message);
    });
}

Installing

Use as ES module:

You can install it via npm or yarn

npm install browser-image-compression --save
# or
yarn add browser-image-compression
import imageCompression from 'browser-image-compression';

(can be used in frameworks like React, Angular, Vue etc)

(work with bundlers like webpack and rollup)

(or) Load UMD js file:

You can download imageCompression from the dist folder.

Alternatively, you can use a CDN like delivrjs:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.1/dist/browser-image-compression.js"></script>

API

Main function

// you should provide one of maxSizeMB, maxWidthOrHeight in the options
const options: Options = { 
  maxSizeMB: number,            // (default: Number.POSITIVE_INFINITY)
  maxWidthOrHeight: number,     // compressedFile will scale down by ratio to a point that width or height is smaller than maxWidthOrHeight (default: undefined)
                                // but, automatically reduce the size to smaller than the maximum Canvas size supported by each browser.
                                // Please check the Caveat part for details.
  onProgress: Function,         // optional, a function takes one progress argument (percentage from 0 to 100) 
  useWebWorker: boolean,        // optional, use multi-thread web worker, fallback to run in main-thread (default: true)
  libURL: string,               // optional, the libURL of this library for importing script in Web Worker (default: https://cdn.jsdelivr.net/npm/browser-image-compression/dist/browser-image-compression.js)
  preserveExif: boolean,        // optional, use preserve Exif metadata for JPEG image e.g., Camera model, Focal length, etc (default: false)

  signal: AbortSignal,          // optional, to abort / cancel the compression

  // following options are for advanced users
  maxIteration: number,         // optional, max number of iteration to compress the image (default: 10)
  exifOrientation: number,      // optional, see https://stackoverflow.com/a/32490603/10395024
  fileType: string,             // optional, fileType override e.g., 'image/jpeg', 'image/png' (default: file.type)
  initialQuality: number,       // optional, initial quality value between 0 and 1 (default: 1)
  alwaysKeepResolution: boolean // optional, only reduce quality, always keep width and height (default: false)
}

Caveat

Each browser limits the maximum size of a browser Canvas object.
So, we resize the image to less than the maximum size that each browser restricts.
(However, the proportion/ratio of the image remains.)

Abort / Cancel Compression

To use this feature, please check the browser compatibility: https://caniuse.com/?search=AbortController

function handleImageUpload(event) {

  var imageFile = event.target.files[0];

  var controller = new AbortController();

  var options = {
    // other options here
    signal: controller.signal,
  }
  imageCompression(imageFile, options)
    .then(function (compressedFile) {
      return uploadToServer(compressedFile); // write your own logic
    })
    .catch(function (error) {
      console.log(error.message); // output: I just want to stop
    });
  
  // simulate abort the compression after 1.5 seconds
  setTimeout(function () {
    controller.abort(new Error('I just want to stop'));
  }, 1500);
}

Helper function

  • for advanced users only, most users won’t need to use the helper functions

 

Contribution

  1. fork the repo and git clone it
  2. run npm run watch # it will watch code change in lib/ folder and generate js in dist/ folder
  3. add/update code in lib/ folder
  4. try the code by opening example/development.html which will load the js in dist/ folder
  5. add/update test in test/ folder
  6. npm run test
  7. push to your forked repo on github
  8. make a pull request to dev branch of this repo
Nandemo Webtools

Leave a Reply