Reputation: 61775
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
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
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
Reputation: 6162
Compute two ratios (with floating point result):
Then,
Upvotes: 2