Resize Image using Javascript

by Tushar Thakare

HTML

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>A Pen by  Tushar Thakare</title>
  
  
  
  
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
  
</head>

<body>

<input type='file' id='input' accept="image/*">
<img id='img' style="height:170px;width:170px;padding:4px;border:1px dashed blue;border-radius:2000px">










</body>

</html>

JavaScript

function resizeImage(file:File, maxWidth:number, maxHeight:number):Promise<Blob> {
    return new Promise((resolve, reject) => {
        let image = new Image();
        image.src = URL.createObjectURL(file);
        image.onload = () => {
            let width = image.width;
            let height = image.height;
            
            if (width <= maxWidth && height <= maxHeight) {
                resolve(file);
            };

            let newWidth;
            let newHeight;

            if (width > height) {
                newHeight = height * (maxWidth / width);
                newWidth = maxWidth;
            } else {
                newWidth = width * (maxHeight / height);
                newHeight = maxHeight;
            }

            let canvas = document.createElement('canvas');
            canvas.width = newWidth;
            canvas.height = newHeight;

            let context = canvas.getContext('2d');

            context.drawImage(image, 0, 0, newWidth, newHeight);

            canvas.toBlob(resolve, file.type);
        };
        image.onerror = reject;
    });
}

document.getElementById('input').addEventListener('change', (o) => {
	//If you don't need to resize the image, you can get the blob to upload from the 
  //FileList (e.g. doUpload(o.target.files[0]);

  if(o.target.files.length > 0) {
  	resizeImage(o.target.files[0], 150, 150).then(blob => {
    	//You can upload the resized image: doUpload(blob)
    	document.getElementById('img').src = URL.createObjectURL(blob);
    }, err => {
    	console.error("Photo error", err);
    });
  }});