jQuery Resize Image Plug-in

Created this plug-in to automatically resize an image based on a maximum width and height. It will scale the image to the correct proportions.

In my application, I used Paul Irish’s imagesLoaded plug in with this to make sure the images were fully loaded before I resized them.

Feel free to use this yourself as is or as a starting point. No license (public domain).

The HTML

<img id="theimage" src="http://test.iministries.org/images/theimage.png" />

The Javascript

$("#theimage").resizeImage({ maxHeight: 200, maxWidth: 200 });

The Plugin Code

(function ($) {
    $.fn.resizeImage = function (options) {
        $(this).css({ width: "auto", height: "auto"}).imagesLoaded(function ($images) {
            $images.each(function () {
                var height = $(this).height();
                var width = $(this).width();
                var maxHeight = options.maxHeight;
                var maxWidth = options.maxWidth;
                if (height > maxHeight || width > maxWidth) {
                    var heightProportion = height / maxHeight;
                    var widthProportion = width / maxWidth;
                    var adjustment = 0;
                    if (heightProportion > 1 || widthProportion > 1) {
                        if (heightProportion > widthProportion)
                            adjustment = 1 / heightProportion;
                        else
                            adjustment = 1 / widthProportion;
                        adjustment = Math.floor(adjustment * 100) / 100 - 0.005;
                        $(this).css({
                            height: Math.round(height * adjustment),
                            width: Math.round(width * adjustment)
                        });
                    }
                }
            });
        });
    }
})(jQuery);

For a sample and the latest version of the code visit the repository on github.


So, what do you think ?