Best fit image height and width calculation algorithm

Very often during web development I needed to resize image, so it would fit in given space / dimensions aka MaxWidth / MaxHeight. Here is a little algorithm, which does a trick.

int MaxWidth = 200, MaxHeight = 400; // restrictions

int w=500, h=600; // current image dimensions

 

float ratio = (float)w / h;

w = MaxWidth;

h = (int)Math.Floor(MaxWidth / ratio);

 

if (h > MaxHeight)

{

    h = MaxHeight;

    w = (int)Math.Floor(MaxHeight * ratio);

}     


Monday, September 29, 2008 | Comments (2) | Add Comment

Comments

Gravatar

Re:Best fit image height and width calculation algorithm

Thanks for posting this! I was trying to do it on my own but couldn't come up with an algorithm that would work. This works perfectly. :)

8/13/2009 9:14:44 PM | by Jeremy
Gravatar

Re:Best fit image height and width calculation algorithm

thax a lot

11/24/2009 2:15:31 AM | by jerome

New Comment

Your Name:
Email (for internal use only):
Subject:
Comment:
 
Code above: