Get started with compressorjs CDN

MIT licensed

Compressor.js is a lightweight library for image and video compression in the browser.

Tags:
  • image
  • compress
  • compressor
  • compressor.js
  • image-compressor
  • lossy-compression
  • javascript
  • front-end
  • web

Stable version

Copied!

How to start using compressorjs CDN


<!DOCTYPE html>
<html>
<head>
  <title>Get started with compressorjs CDN - cdnhub.io</title>
  <script src="https://cdn.cdnhub.io/compressorjs/1.2.1/compressor.min.js"></script>
</head>
<body>
  <button id="compress-button">Compress Image</button>
  <img id="input-image" src="path/to/your/image.jpg" alt="Input Image">
  <canvas id="output-canvas"></canvas>

  <script>
    const compressButton = document.getElementById('compress-button');
    const inputImage = document.getElementById('input-image');
    const outputCanvas = document.getElementById('output-canvas');

    compressButton.addEventListener('click', async () => {
      const image = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            resolve(img);
          };
        };
        reader.readAsDataURL(inputImage.files[0]);
      });

      const compressor = new compressorjs.default({
        width: 320,
        height: 240,
        quality: 0.8,
        resize: compressorjs.METHOD.FAST,
      });

      const compressedImage = await compressor.compress(image);
      outputCanvas.width = compressedImage.width;
      outputCanvas.height = compressedImage.height;
      const context = outputCanvas.getContext('2d');
      context.drawImage(compressedImage, 0, 0);
    });
  </script>
</body>
</html>
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!

All versions