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);

}     


Posted on Monday, September 29, 2008 by | Comments (3) | 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. :)

Posted on 8/13/2009 9:14:44 PM by Jeremy #
Gravatar

Re:Best fit image height and width calculation algorithm

thax a lot

Posted on 11/24/2009 2:15:31 AM by jerome #
Gravatar

Re: Best fit image height and width calculation algorithm

algoritm bestfit in c#

Posted on 11/13/2012 4:20:13 AM by saeid #

New Comment

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

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5