Image Resizing With jQuery

I just found a problem when I want to display image in a web page, especially for image with large dimensions, e.g. : 1024 x 768 pixels. I need this image to be automatically scaled to smaller dimensions, e.g. : 400px x 400px.
There are some solutions that I can think of, such as : get the image dimensions (width & height) using Java then pass the values to JSP. But I think it will take time. So I decided to use javascript/jQuery and found this solution from stackoverflow :

  • Import jQuery source
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>
  • Add this script to scale image with css-class ‘resize-img’ property
    $(document).ready(function() {
    	// resize image if image's width/height is larger than 400px
    	$('img.resize-img').each(function(){
    	//$(this).load(function(){
    
    		var maxWidth = 400; // Max width for the image
    		var maxHeight = 400;    // Max height for the image
    		var ratio = 0;  // Used for aspect ratio
    		var width = $(this).width();    // Current image width
    		var height = $(this).height();  // Current image height
    
    		// Check if the current width is larger than the max
    		if(width > maxWidth){
    			ratio = maxWidth / width;   // get ratio for scaling image
    			$(this).css("width", maxWidth); // Set new width
    			$(this).css("height", height * ratio);  // Scale height based on ratio
    			height = height * ratio;    // Reset height to match scaled image
    		}
    
    		var width = $(this).width();    // Current image width
    		var height = $(this).height();  // Current image height
    
    		// Check if current height is larger than max
    		if(height > maxHeight){
    			ratio = maxHeight / height; // get ratio for scaling image
    			$(this).css("height", maxHeight);   // Set new height
    			$(this).css("width", width * ratio);    // Scale width based on ratio
    			width = width * ratio;    // Reset width to match scaled image
    		}
       // });
    	});
    });
    
  • After that, define image tag & add property class=’resize-img’
    <img alt="" src="{/path/to/image}" class="resize-img" />

You can see the example here.

Source :

http://stackoverflow.com/questions/1143517/jquery-resizing-image

http://haslayout.net/css-tuts/CSS-Proportional-Image-Scale


Warning: file_get_contents(https://graph.facebook.com/comments/?ids=http://fahmijafar.net/2011/11/01/image-resizing-with-jquery/): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/fahmij01/public_html/wp-content/plugins/facebook-like-and-comment/comments.php on line 17

Warning: Invalid argument supplied for foreach() in /home/fahmij01/public_html/wp-content/plugins/facebook-like-and-comment/comments.php on line 19