Best fit image height and width calculation algorithm

Very often during web development, I needed to resize an image, so it would fit in a given space or 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 September 29, 2008 by


Posted on 8/13/2009 09:14:44 PM by Jeremy

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 11/24/2009 02:15:31 AM by jerome

thax a lot

Posted on 11/13/2012 04:18:52 AM by saeid

bestfit algoritm inc#