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

How to decode JWT token

Hey, you can decode JWT (JSON Web Token) by using this method. function   parseJwt ( token )  {      try  {        return   JSON . parse ( atob (token . split ( ' . ' )[ 1 ]));     }  catch  (e) {        return   null ;     }   };   parseJwt ( " eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZ S   I6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6ImNmNTMxNjgxLWZkZWQtNDQ0My1hNjQ1LTQ4NThh  NDQ1YzU1ZSIsImlhdCI6MTU5MDA1NTQ3NSwiZXhwIjoxNTkwMDU5MDc1fQ.H1QW0pQVfdW3nbwA- GfHGKP   cu1 - qyuh99UlXIEPBQJ8 " ) ; Output: {   "sub": "1234567890",   "name": "John Doe",   "admin": true,   "jti": "cf531681-fded-4443-a645-4858a445c55e",   "iat": 1590055475,   "exp": 1590059075 }