Compressor.js

1.3.0 · active · verified Sun Apr 19

Compressor.js is a client-side JavaScript image compression library that leverages the browser's native `HTMLCanvasElement.toBlob()` method for its core functionality. It performs lossy, asynchronous compression, meaning results can vary slightly across different web browsers and privacy settings. Primarily designed for pre-compressing images on the client before upload, it provides a straightforward API for handling `File` or `Blob` objects. The current stable version is 1.3.0, and the project appears actively maintained with a steady cadence of minor updates addressing bug fixes and introducing new options. Its key differentiator is its reliance on native browser APIs, simplifying its footprint but also making its compression effects browser-dependent. It ships with TypeScript types.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to select an image file from an input, compress it using Compressor.js with specific quality and dimension constraints, and then preview the compressed image or prepare it for upload.

import Compressor from 'compressorjs';

// Create a dummy file input for demonstration purposes
const inputElement = document.createElement('input');
inputElement.setAttribute('type', 'file');
inputElement.setAttribute('id', 'fileInput');
inputElement.setAttribute('accept', 'image/*');
document.body.appendChild(inputElement);

document.getElementById('fileInput')?.addEventListener('change', (e) => {
  const target = e.target as HTMLInputElement;
  const file = target.files?.[0];

  if (!file) {
    console.log('No file selected.');
    return;
  }

  new Compressor(file, {
    quality: 0.6,
    maxWidth: 800,
    maxHeight: 600,
    // Output the original image instead of the compressed one if the compressed size is larger.
    strict: true,
    success(result) {
      console.log('Compression successful! Compressed file:', result);
      // The 'result' is a File object (or Blob in older versions).
      // You can now upload this 'result' to your server.
      const formData = new FormData();
      formData.append('compressedImage', result, result.name);

      // Example of what you might do next (e.g., using fetch or axios):
      // fetch('/path/to/upload', { method: 'POST', body: formData })
      //   .then(response => console.log('Upload success', response))
      //   .catch(error => console.error('Upload error', error));

      const reader = new FileReader();
      reader.onload = (event) => {
        const img = document.createElement('img');
        img.src = event.target?.result as string;
        img.style.maxWidth = '200px';
        document.body.appendChild(img);
        console.log('Displaying compressed image preview.');
      };
      reader.readAsDataURL(result);
    },
    error(err) {
      console.error('Compression error:', err.message);
    },
  });
});

view raw JSON →