Get dimensions of an image and change it in javascript

If you are ever faced with the problem of finding the true size of an image in a web page and you want to resize it dynamically then the code below is an example.

1.It gets the actual size of the image. i.e it will bypass the height and width attributes set in the IMG tag or the dimensions set to the image by CSS.

2.It can alter the displayable height and width of the image at runtime. The trick is to use the Image object in javascript and attach it to the image url in the target IMG tag.

The javascript code is given below. It uses JQuery.

		$(document).ready(function() {
			imgSize();
		}
		);	
		function imgSize() {
			var src = $('#phoneImage').attr('src');
			var ow = $('#phoneImage').attr('width');
			var oh = $('#phoneImage').attr('height');
			var newImg = new Image();
		    newImg.src = src;
		    var height = newImg.height;
		    var width = newImg.width;
		    p = $(newImg).ready(function(){
					var nw = newImg.width;
					var nh = newImg.height;
					
					if (parseInt(nw) < parseInt(ow) )
						$('#phoneImage').attr("width", "");
					if (parseInt(nh) < parseInt(oh) )
						$('#phoneImage').attr("height", "");
		        return {width: newImg.width, height: newImg.height};
		    });
		

			
					
		}
The example IMG tag is shown below

<img id="phoneImage" align = center src="myimages/demoimage.jpg"  width="150" height="190"/>
The sample logic used in the javascript is that if the the actual height or width of the image is lesser than the assigned height and width attribute tags , then it assigns the original width or height of the image by making that attribute blank.

Be the first to comment

Leave a Reply

Your email address will not be published.


*