How to constrain an image's dimensions while maintaining its ratio

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 w0×h0, 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’ ≤ w0

(3) h’ ≤ h0

Note that that the ratio of the constraining box w0/h0 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/φ ≤ w0 , h/φ ≤ h0  ⇒ w/w0 ≤ φ , h/h0 ≤ φ .

From the last statement it is clear that all we need to do is to choose φ = max[ w/w0h/h0].

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

1)  φ = max[ w/w0h/h0]

2)  w’ = w/φ

3) h’ = h/φ

Or, if you please, the conditional equivalent:

Is w/wh/h0 ? 

then:  w’ = w0 , h’ = w0·h/w

or else:  w’ = h0·w/h , h’ = h0

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>