开发者

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.


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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜