Tom Gullen
Tom Gullen

Reputation: 61775

Maths to resize an image into bounds of max height and max width

Given an image:

maxWidth = 400;
maxHeight = 200;
width = photo.Width;
height = photo.Height;

How would I go about scaling the image if either dimension exceeds the maximum properties?

Here are some test cases:

300x300  :   Too tall, but width ok.
500x200  :   Too wide, but height ok.
650x300  :   Too tall and too wide
300x190  :   Fine, don't resize

I'm having trouble visualising the maths for this, sorry if it's too simple! The case giving me most trouble is the one where both dimensions exceed the max allowed.

Upvotes: 3

Views: 1573

Answers (3)

Kim Alders
Kim Alders

Reputation: 97

My maths are quite bad, but, assuming you want a proportional scale, i'd solve it like this:

if maxWidth < photo.Width
    width = 'too big'
if maxHeight < photo.Height
    height = 'too big'

if height == 'to big' & width == 'too big' 
    x = photo.Width / maxWidth;
    y = photo.Height / maxHeight;
    if x > y
        scale_by_width(photo)
    else
        scale_by_height(photo)

elseif height == 'too big'
    scale_by_height(photo)

elseif width == 'too big'
    scale_by_width(photo)

else
    do_nothing

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 186068

Separately compute the vertical and horizontal scaling required, then choose the smaller of the two and clamp the result to a maximum of 1. In code:

scale = min(1, min(maxWidth/photo.Width, maxHeight/photo.Height))

Make sure the division operations use floating-point arithmetic. How to do this varies from language to language. In C/Java/C# and their ilk, cast one of the operands to float.

Upvotes: 11

rwong
rwong

Reputation: 6162

Compute two ratios (with floating point result):

  • input width divided by maximum allowed width
  • input height divided by maximum allowed height

Then,

  • if both ratios < 1.0, don't resize.
  • if one of the ratio > 1.0, scale down by that factor.
  • if both ratios > 1.0, scale down by the bigger of the two factors.

Upvotes: 2

Related Questions