I have a script, that's pretty huge for an actual simple task, because it's nested very often. What it does is this:
- get the current size of an image
- get the new maximum dimensions
- calculate the dimensions the image is going to be resized to (aspect ratio is always kept):
- if image is smaller than new dimensions: keep original size
- if max new dimensions have an x and y-value: scale image to fit both values
- if max new dimensions have only a x-value: scale to fit at least x
- if max new dimensions have only a y-value: scale to fit at least y
This is the script:
//example values, whereas 'new' is the maximum range for the new image
$dimensions = array(1920,1200);
$dimensionsNew = array(160, 0);
// percentage the image must be scaled
$percentages = array(0,0);
//calculate scale range
if ($dimensionsNew[0] != 0) $percentages[0] = $dimensions[0] / $dimensionsNew[0];
if ($dimensionsNew[1] != 0) $percentages[1] = $dimensions[1] / $dimensionsNew[1];
//get new dimensions
if ( ($dimensions[0] <= $dimensionsNew[0]) && ($dimensions[1] <= $dimensionsNew[1]) ) {
$dimensionsNew[0] = $dimensions[0];
$dimensionsNew[1] = $dimensions[1];
} elseif ($dimensionsNew[0] == 0) {
if ($dimensions[1] <= $dimensionsNew[1]) {
$dimensionsNew[0] = $dimensions[0];
$dimensionsNew[1] = $dimensions[1];
} else {
$dimensionsNew[0] = ceil($dimensions[0] / $percentages[1]);
}
} elseif ($dimensionsNew[1] == 0) {
if ($dimensions[0] <= $dimensionsNew[0]) {
$dimensionsNew[0] = $dimensions[0];
$dimensionsNew[1] = $dimensions[1];
} else {
$dimensionsNew[1] = ceil($dimensions[1] / $percentages[0]);
}
} elseif ($percentages[0] < $percentages[1]) {
$dimensionsNew[1] = ceil($dimensions[1] / $percentages[1]);
} else {
$dimensionsNew[0] = ceil($dimensions[0] / $percentages[0]);
}
It does what it should do. But is there an easier way of doing this? I think I looked at this code too often and can't find a way to optimize.