Wednesday, July 18, 2012

Resize images proportionally keeping the aspect ratio

Here is the solution with jQuery -
Fiddle Demo: http://jsfiddle.net/dipaks2011/3yfgk/

CSS //to center and vertically middle align the image
div{ 
    width: 140px; 
    height: 140px; 
    border: 1px solid #f00; 
    text-align: center; 
    vertical-align: middle; 
    display: table-cell;
}
Note: display: table-cell; supports IE8+

HTML
<div>
    <img src="http://www.htmlgoodies.com/img/2010/11/jquery.jpg" />
</div>
jQuery
<script type="text/javascript">
    $(function(){
        var max_size = 130;
        $("div img").each(function() {
            if ($(this).height() > $(this).width()) {
                var h = max_size;
                var w = Math.ceil($(this).width() / $(this).height() * max_size); 
            }
           else{
               var w = max_size;
               var h = Math.ceil($(this).height() / $(this).width() * max_size);
           }
           $(this).css({'height': h, 'width': w});
        });
    });
</script>