Search code examples
javascriptmathscaleimage-resizingpercentage

Javascript Image Resize Calculation


Let's say I have an image that is 1920 x 1280.

I'm using a slider to scale down the image, which goes from 100% to 0%, where 100% is the original size and 0% is the minimum size.

The image can be no smaller than 350 in either height, or width, so 0% should equate to this minimum size.

What formula would I use to calculate the new dimensions? If you could explain the logic, that would be helpful.

I'm certain this is an SAT question that I failed...


Solution

  • var min=Math.min(width,height);
    var result=Math.max(min * (percentage/100),350);
    var newHeight=(result/min) * height;
    var newWidth=(result/min) * width;
    

    Percentage between 0 and 1 (can be altered to be 0 - 100 integers instead of 0 to 1 floats). Other words are describing themselves. Maybe useful as a function:

    function ff(height,width,percentage){    
        var min=Math.min(width,height);
        var result=Math.max(min*(percentage/100),350);
        var newHeight=(result/min) * height;
        var newWidth=(result/min) * width; 
        return [newWidth,newHeight]; 
     }
    

    No math is needed for this. Css is already capable of these things.

    min-width: 350px;
    min-height:350px;
    width: x% (or height: ... x%)
    in a 1920 by 1280 sized div.