# 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 Viktar Karpach