Compress Image in JS

How to compress image in JavaScript?

·

1 min read

You can compress image by using this method.

function compressImage(imageUrl) {
    let image = new Image();

    image.onload = () => {
      let canvas = document.createElement('canvas');
      let maxSize = 1504; // Define Size of Image
      let width = image.width;
      let height = image.height;

      if (width > height && width > maxSize) {
        height *= maxSize / width;
        width = maxSize;
      } else if (height > maxSize) {
        width *= maxSize / height;
        height = maxSize;
      }

      canvas.width = width;
      canvas.height = height;
      canvas.getContext('2d').drawImage(image, 0, 0, width, height);
      let base64Image = canvas.toDataURL('image/jpeg').split(",")[1];
    }

    image.src = imageUrl;
  }