jQuery: resize images proportionally

jQuery: resize images proportionally

How to proportionally resize images with jQuery.

To proportionally resize images with jQuery we only need to calculate the existing ratios between maximum widths and heights and the original widths and heights of the images. This is, in fact, a matter of division. The next step is to multiply this ratio by the original width or height, depending on their relationship with the maximum widths and heights (greater or less than). In this article we'll see how to accomplish this task by creating a simple jQuery plugin.

Our code is as follows:

(function($) {
    $.fn.imageResize = function(options) {

        var that = this;
        var settings = {
            width: 150,
            height: 150
        };
        options = $.extend(settings, options);

        if (!that.is('img')) {
            return;
        }

        return that.each(function() {

            var maxWidth = options.width;
            var maxHeight = options.height;
            var ratio = 0;
            var width = $(that).width();
            var height = $(that).height();

            if (width > maxWidth) {
                ratio = maxWidth / width;
                $(that).css('width', maxWidth);
                $(that).css('height', height * ratio);

            }

            if (height > maxHeight) {
                ratio = maxHeight / height;
                $(that).css('height', maxHeight);
                $(that).css('width', width * ratio);

            }

        });

    };
})(jQuery);

imageResize() is the name of our plugin. It accepts two options (maximum width and height) to properly calculate the returned dimensions of the scaled image.

If the original width of the image is greater than the maximum width, then the height of the scaled image will result from the multiplication of the original height by the calculated ratio.

If the original height of the image is greater than the maximum height, then the width of the scaled image will result from the multiplication of the original width by the calculated ratio.

Again, the calculated ratio is simply the result of the division of the original dimensions by the maximum dimensions set by the plugin options.

An example:

$('img', '#original').click(function() {
    $(this).imageResize();
});​

You can see the demo below.

Demo

Live demo