How to resize and crop an image using Typescript

In this article, I will share a simple snippet in Typescript, that you can easily convert to Javascript, to resize and crop images without relying on any third-party libraries.

This code snippet first prompts you to select a local image using an HTMLInputElement.

Once an image is selected, using the FileReader API, it loads the image to an HTMLImageElement, without adding it to the HTML DOM.

Once the image is loaded from the local file system into the HTMLImageElement, we call the javascript function resizeAndSquareImage.

This function performs the image resizing and cropping of the image so it becomes a perfectly square image!

The squared image is written to the HTMLCanvasElement.

Here is the HTML:

<html>
<body>

<label for="changeImage">Choose the image you want to square:</label>
<p/>
<input type="file"
       id="changeImage" name="changeImage"
       accept="image/png, image/jpeg" imgid="squaredImage" >
	
<p/>	
<canvas id="squaredImage"  url="/no-image-selected.jpg"  width="256" height="256"/>
<p/>
</body>
</html>

And the Javascript/Typescript code:

let changeImage = function (evt: React.ChangeEvent<{ name?: string; value: unknown }>) {
    var tgt = evt.target || window.event.srcElement,
        files = tgt.files;

    // FileReader support
    if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = function () {
			let targetCanvas = document.getElementById(evt.target.getAttribute("imgid"));
			resizeAndSquareImage(fr.result, targetCanvas);
        }
        fr.readAsDataURL(files[0]);
    }
}

function resizeAndSquareImage(imageUrl:string, targetCanvas:HTMLCanvasElement) {
    // this image will hold our source image data
    const inputImage:HTMLImageElement = new Image();
    console.log("resizeAndSquareImage called");
    // we want to wait for our image to load
    let result = inputImage.onload = () => {
	const imgSize:number = Math.min(inputImage.width, inputImage.height);
        const left:number = (inputImage.width - imgSize) / 2;
        const top:number = (inputImage.height - imgSize) / 2;
        const ctx:CanvasRenderingContext2D = targetCanvas.getContext("2d");
	ctx.drawImage(inputImage, left, top, imgSize, imgSize, 0, 0, targetCanvas.width, targetCanvas.height);
	  return targetCanvas;
     };
     inputImage.src = imageUrl;
     return result;
}


document.getElementById("changeImage").onchange = changeImage;

And here is the JSFiddle link so that you can try this code in real-time:

https://jsfiddle.net/kdq7u1er/

Hope you find this short blog post useful!


Posted

in

by