Skip to main content

How to compress image in JS (JavaScript)

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;
  }

Comments

Popular posts from this blog

Git SSH Setup on Gitlab

You can setup your gitlab account with SSH Key Step-1:  Open Git Bash in Windows OS OR in Mac OS open Terminal Step-2: Run below Command (Replace your mail address)           ssh-keygen -t rsa -C " youremail@domain.com " -b 4096 It will ask few questions. You have just Enter. Step-2: Run the below command to read SSH Key      cat ~/.ssh/id_rsa.pub Copy your SSH key until your email address. Step-3: Open you gitlab Account  Go to Settings  Click on 'SSH Keys' (Left Bottom Side) Paste SSH Key If you want to set expiry of your SSH Key then you can set an expiry date. Then Click on 'Add Key' Button Finish