Search code examples
javascriptmathdimensionsarea

resize image by area


I am trying to write a javascript function to resize an image based on a given area (or in my case (somewhat inaccurate) 'average dimension' since that's easier to think in terms of. Rather than feeding in maximum height and width, I want to feed in maximum area so that long or narrow images will appear visually to be roughly the same size.

enter image description here

I'm getting really caught on the math aspect of it, though... just how to logic it, as I haven't done much math of late.

Basically, given an aspect ratio I want to determine the maximum size within an area.

Something like this:

function resizeImgByArea(img, avgDimension){
    var w = $(img).width();
    var h = $(img).height();
    var ratio = w/h;
    var area = avgDimension * avgDimension;
    var targetHeight //something involving ratio and area
    var targetWidth //something involving ratio and area
    $(img).width(targetWidth);
    $(img).height(targetHeight);
}

Not sure if this is on topic here, but I'm not able to brain it.


Solution

  • Here is the function I came up with that's simpler than some mentioned and does what I need. It constrains to a set maxWidth, but not height because of the particular requirements I was using.. it would probly be appropriate to throw on a maxHeight as well as well as some cleanup, but it gets 'er done.

    function resizeImgByArea(imgId, avgDimension){
       var node, w, h, oldArea, oldAvgDimension, multiplicator, targetHeight, targetWidth, defAvgDimension;
       node = $('#' + imgId);
       node.css('width', '').css('height', '');
       var maxW = $('#' + imgId).css('maxWidth');
       if (maxW){
           defAvgDimension = maxW;
       } else {
           defAvgDimension = 200;
       }
       avgDimension = (typeof avgDimension == "undefined")?'defAvgDimension':avgDimension;
       w = node.width();
       h = node.height();
       oldArea = w*h;
       oldAvgDimension = Math.sqrt(oldArea);
       if (oldAvgDimension > avgDimension){
           multiplicator = avgDimension / oldAvgDimension;
           targetHeight = h * multiplicator;
           targetWidth = w * multiplicator;
           node.width(targetWidth);
           node.height(targetHeight);
       }
    }