Home

Awesome

Compressor.js

Coverage Status Downloads Version Gzip Size

JavaScript image compressor. Uses the Browser's native canvas.toBlob API to do the compression work, which means it is lossy compression, asynchronous, and has different compression effects in different browsers. Generally use this to precompress a image on the client side before uploading it.

Table of contents

Main

dist/
├── compressor.js        (UMD)
├── compressor.min.js    (UMD, compressed)
├── compressor.common.js (CommonJS, default)
└── compressor.esm.js    (ES Module)

Getting started

Install

npm install compressorjs

Usage

Syntax

new Compressor(file[, options])

file

The target image file for compressing.

options

The options for compressing. Check out the available options.

Example

<input type="file" id="file" accept="image/*">
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,

    // The compression process is asynchronous,
    // which means you have to access the `result` in the `success` hook function.
    success(result) {
      const formData = new FormData();

      // The third parameter is required for server
      formData.append('file', result, result.name);

      // Send the compressed image file to server with XMLHttpRequest.
      axios.post('/path/to/upload', formData).then(() => {
        console.log('Upload success');
      });
    },
    error(err) {
      console.log(err.message);
    },
  });

});

⬆ back to top

Options

You may set compressor options with new Compressor(file, options). If you want to change the global default options, You may use Compressor.setDefaults(options).

strict

Indicates whether to output the original image instead of the compressed one when the size of the compressed image is greater than the original one's, except the following cases:

checkOrientation

Indicates whether to read the image's Exif Orientation value (JPEG image only), and then rotate or flip the image automatically with the value.

Notes:

retainExif

Indicates whether to retain the image's Exif information after compressed.

maxWidth

The max-width of the output image. The value should be greater than 0.

Avoid getting a blank output image, you might need to set the maxWidth and maxHeight options to limited numbers, because of the size limits of a canvas element, recommend to use 4096 or lesser.

maxHeight

The max height of the output image. The value should be greater than 0.

minWidth

The min-width of the output image. The value should be greater than 0 and should not be greater than the maxWidth.

minHeight

The min-height of the output image. The value should be greater than 0 and should not be greater than the maxHeight.

width

The width of the output image. If not specified, the natural width of the original image will be used, or if the height option is set, the width will be computed automatically by the natural aspect ratio.

height

The height of the output image. If not specified, the natural height of the original image will be used, or if the width option is set, the height will be computed automatically by the natural aspect ratio.

resize

Sets how the size of the image should be resized to the container specified by the width and height options.

Note: This option only available when both the width and height options are specified.

quality

The quality of the output image. It must be a number between 0 and 1. If this argument is anything else, the default values 0.92 and 0.80 are used for image/jpeg and image/webp respectively. Other arguments are ignored. Be careful to use 1 as it may make the size of the output image become larger.

Note: This option only available for image/jpeg and image/webp images.

Check out canvas.toBlob for more detail.

Examples:

QualityInput sizeOutput sizeCompression ratioDescription
02.12 MB114.61 KB94.72%-
0.22.12 MB349.57 KB83.90%-
0.42.12 MB517.10 KB76.18%-
0.62.12 MB694.99 KB67.99%Recommend
0.82.12 MB1.14 MB46.41%Recommend
12.12 MB2.12 MB0%Not recommend
NaN2.12 MB2.01 MB5.02%-

mimeType

The mime type of the output image. By default, the original mime type of the source image file will be used.

convertTypes

Files whose file type is included in this list, and whose file size exceeds the convertSize value will be converted to JPEGs.

For image file type support, see the Image file type and format guide.

convertSize

Files whose file type is included in the convertTypes list, and whose file size exceeds this value will be converted to JPEGs. To disable this, just set the value to Infinity.

Examples:

convertSizeInput size (type)Output size (type)Compression ratio
5 MB1.87 MB (PNG)1.87 MB (PNG)0%
5 MB5.66 MB (PNG)450.24 KB (JPEG)92.23%
5 MB9.74 MB (PNG)883.89 KB (JPEG)91.14%

beforeDraw(context, canvas)

The hook function to execute before drawing the image into the canvas for compression.

new Compressor(file, {
  beforeDraw(context, canvas) {
    context.fillStyle = '#fff';
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.filter = 'grayscale(100%)';
  },
});

drew(context, canvas)

The hook function to execute after drawing the image into the canvas for compression.

new Compressor(file, {
  drew(context, canvas) {
    context.fillStyle = '#fff';
    context.font = '2rem serif';
    context.fillText('watermark', 20, canvas.height - 20);
  },
});

success(result)

The hook function to execute when successful to compress the image.

error(err)

The hook function executes when fails to compress the image.

⬆ back to top

Methods

abort()

Abort the compression process.

const compressor = new Compressor(file);

// Do something...
compressor.abort();

No conflict

If you have to use another compressor with the same namespace, just call the Compressor.noConflict static method to revert to it.

<script src="other-compressor.js"></script>
<script src="compressor.js"></script>
<script>
  Compressor.noConflict();
  // Code that uses other `Compressor` can follow here.
</script>

Browser support

Contributing

Please read through our contributing guidelines.

Versioning

Maintained under the Semantic Versioning guidelines.

License

MIT © Chen Fengyuan

⬆ back to top