How to resize images proportionally / keeping the aspect ratio?
I think this is a really cool method:
/** * Conserve aspect ratio of the original region. Useful when shrinking/enlarging * images to fit into a certain area. * * @param {Number} srcWidth width of source image * @param {Number} srcHeight height of source image * @param {Number} maxWidth maximum available width * @param {Number} maxHeight maximum available height * @return {Object} { width, height } */function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) { var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); return { width: srcWidth*ratio, height: srcHeight*ratio }; }
Have a look at this piece of code from http://ericjuden.com/2009/07/jquery-image-resize/
$(document).ready(function() { $('.story-small img').each(function() { var maxWidth = 100; // Max width for the image var maxHeight = 100; // 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 width = width * ratio; // Reset width to match scaled image } // 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 height = height * ratio; // Reset height to match scaled image } });});
If I understand the question correctly, you don't even need jQuery for this. Shrinking the image proportionally on the client can be done with CSS alone: just set its max-width
and max-height
to 100%
.
<div style="height: 100px"><img src="http://www.getdigital.de/images/produkte/t4/t4_css_sucks2.jpg" style="max-height: 100%; max-width: 100%"></div>
Here's the fiddle: http://jsfiddle.net/9EQ5c/