Search code examples
javascriptjqueryimagescale

jQuery resize to aspect ratio


How would I resize a image in jQuery to a consistent aspect ratio. For example setting maximum height and have the width resize correctly. Thanks.


Solution

  • You could calculate this manually,

    i.e.:

    function GetWidth(newHeight,orginalWidth,originalHeight)
    {
    if(currentHeight == 0)return newHeight;
    var aspectRatio = currentWidth / currentHeight;
    return newHeight * aspectRatio;
    }
    

    Make sure you use the ORIGINAL values for the image otherwise it will degrade over time.

    EDIT: example jQuery version (not tested)

    jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
        var aspectRatio = $(this).data('aspectRatio');
        if (aspectRatio == undefined) {
            aspectRatio = $(this).width() / $(this).height();
            $(this).data('aspectRatio', aspectRatio);
        }
        $(this).height(newHeight); 
        $(this).width(parseInt(newHeight * aspectRatio));
    }