Hey everyone, I have a php script to resize images to a certain size, if the aspect is the same it just resizes them, but if it's different it crops them first. I just wanted to check my logic was correct and that this would calculate the relevant dimensions for all source and destination image sizes:
$sourceratio = $actualsourcewidth / $actualsourceheight;
$targetratio = $targetwidth / $targetheight;
if ($targetratio < $sourceratio)
{
$srcheight = $actualsourceheight;
$srcwidth = $actualsourceheight * $targetratio;
$srcy = 0;
$srcx = floor(($actualsourcewidth - $srcwidth) / 2);
$srcwidth = floor($srcwidth);
} else if ($targetratio > $sourceratio)
{
$srcwidth = $actualsourcewidth;
$srcheight = $actualsourcewidth / $targetratio;
$srcy = floor(($actualsourceheight - $srcheight) / 2);
$srcx = 0;
$srcheight = floor($srcheight);
} else
{
// Same aspect ratio so you can resize the image without cropping
$srcheight = $actualsourceheight;
$srcwidth = $actualsourcewidth;
$srcx = 0;
$srcy = 0;
}
From what i can work out this should catch all eventualities and produce starting x, y coordinates ($srcx
and $srcy
) and source dimensions ($srcwidth
, $srcheight
) which can then be passed into imagecopyresampled
.
The main thing I wanted to check was that the ratio check will prevent $srcheight
and $srcwidth
from ever being larger than the original width/height as this would break it, but I don't think it will?
Thanks very much as ever everyone!
Dave