I know, this is not nuclear physics, but it tricks my mind every once in a while when this occurs to me.

Let’s assume the general case of an image with dimensions w×h, and that you need to scale it down so that it fits within a certain rectangle sizing w_{0}×h_{0}, while its sides maintain the same ratio R=w/h.

In other words, we need to calculate a new pair of dimensions w’×h’ for our image, for which the following conditions must be satisfied:

(1) w’/h’ = w/h = R

(2) w’ ≤ w_{0}

_{}(3) h’ ≤ h_{0}

_{}Note that that the ratio of the constraining box w_{0}/h_{0} is irrelevant to the ratio of the image R.

From the first of the above conditions (1) we get:

w’/h’ = w/h ⇒ w’·h = w·h’ ⇒ w’/w = h’/h = φ

which means that both the width (w) and the height (h) of the image must be scaled by the same factor φ; thus the problem is pretty much reduced to simply calculating the scaling factor φ.

Let’s take it a bit further by combining the last finding with the inequations (2) and (3):

w’/w = h’/h = φ ⇒ w’ = w/φ , h’ = h/φ ⇒ w/φ ≤ w_{0} , h/φ ≤ h_{0} ⇒ w/w_{0} ≤ φ , h/h_{0} ≤ φ .

From the last statement it is clear that all we need to do is to choose φ = max[ w/w_{0}, h/h_{0}].

To summarize, these are the steps we need to take:

1) φ = max[ w/w_{0}, h/h_{0}]

2) w’ = w/φ

3) h’ = h/φ

Or, if you please, the conditional equivalent:

Is w/w_{0 }> h/h_{0} ?

then: w’ = w_{0} , h’ = w_{0}·h/w

or else: w’ = h_{0}·w/h , h’ = h_{0}