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