$curRatio = $W1/$H1; $maxRatio = $MaxW/$MaxH; if($curRatio > $maxRatio) { $newW = $MaxW; $newH = $currH * ($MaxW/$W1); } else { $newH = $MaxW; $newW = $currW* ($MaxH/$H1); }