Get Width & Height of Image using Javascript before Uploading it (When you onchange on INPUT element)

You can get the width and height of the image in Javascript easily. Simply you need to use onchange event of Javascript on input[type=file].

Steps:-

  • Create a blob URL of the uploaded file.
  • Then create a HTML5 new Image() object, set BLOB url to its src.
  • Apply onload event on new Image() object. So, you can know its width and height when it is completely loaded.
  • Finally, access the width and height properties of the new Image() object.

Example-

<!DOCTYPE html>
<html lang="en-US">
<head>
	<title>Check image size (width & height) in Javascript when you onchange on input element</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="p-5">

	<div class="custom-file w-25">
	<input type="file" class="custom-file-input" accept="image/*" id="upload-file">
	<label for="upload" class="custom-file-label">Choose Images</label>
	</div>

<script>

var upload = document.querySelector("#upload-file");
upload.onchange = function()
{
		var url = URL.createObjectURL(this.files[0]);
		var img = new Image();
		img.src = url;
		img.onload = function()
		{
			alert("Width: "+this.width+" Height: "+this.height);
		}
		img.remove();
}

</script>
</body>
</html>

Leave a Comment