// Set original size as default return dimension.
$dimension = new MyDimension($width, $height);
// Check if original size is bigger than max size.
if ($width <= $maxWidth && $height <= $maxHeight) {
return $dimension;
}
// We need to calculate the maximum best fit dimension.
// Calculate orignal and maximum ratio.
$originalRatio = $width/$height;
$maxRatio = $maxWidth/$maxHeight;
// Based on the ratios, calculate new width and height
if ($maxRatio < $originalRatio) {
// Best fit ratio for width
$dimension->setWidth($maxWidth);
// Only if ratio is on, height must be calculated on ratio
if ($regardRatio) {
$dimension->setHeight(round($maxWidth/$originalRatio));
}
} else {
// Best fit ratio for height
$dimension->setHeight($maxHeight);
// Only if ratio is on, width must be calculated on ratio
if ($regardRatio) {
$dimension->setWidth(round($maxHeight*$originalRatio));
}
}
return $dimension;