Search code examples
crop

How To Calculate Scale Factor Of Image Based On Max Width and Height Of Different Sizes


I'm trying to work out a simple calculation for working out a scale factor so that an image can fit perfectly inside a container size without stretching. This means that the original image may have to overflow the container it needs to fit in, this is fine.

The problem is the image can be of any size, it can be larger than the container in both W and H, larger in just W, larger in just H or smaller in any of those situations.

So let's say for example we have the following containing boxes:

500x500 500x1000 1000x500 300x300 200x50 50x200

and i want an image of 500x500 to fit inside them all but maintaining it's own ratio; so it will overflow some of those containers in some directions but not others.

It doesn't matter what language the code is in, i'm using JS at the moment, it's just the calculation behind it that i'm struggling with. If there was only one size container it wouldn't be too much of a problem but i'm struggling to find a one size fits all formula for this.


Solution

  • Further to the comments, the solution can be rephrased as such:

    • Step 1 If the picture height is smaller than that of the container, upscale to fit.
    • Step 2 If the picture width is smaller than that of container, further upscale to fit.
    • Step 3 If any of step 1 and step 2 hit true, go to Step 5.
    • Step 4 take the smallest of (pic height - container height) and (pic width - container width). Downscale.
    • Step 5 Crop excess

    Done

    Note that a total of 0 or 1 upscaling or downscaling should be done at all and keeping original ratio.