开发者

Is this logic for resizing/cropping images correct (in php but it's about the logic rather than the code)

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


It seems to work. I would refactor it some, initializing the variables and extracting them. This eliminates the need for the last else block and makes the code cleaner to read.

$sourceratio = $actualsourcewidth / $actualsourceheight;
$targetratio = $targetwidth / $targetheight;
$srcx = 0;
$srcy = 0;
$srcheight = $actualsourceheight;
$srcwidth = $actualsourcewidth;

if ($targetratio < $sourceratio)
{
    $srcwidth = $actualsourceheight * $targetratio;
    $srcx = floor(($actualsourcewidth - $srcwidth) / 2);
    $srcwidth = floor($srcwidth);
} else if ($targetratio > $sourceratio)
{
    $srcheight = $actualsourcewidth / $targetratio;
    $srcy = floor(($actualsourceheight - $srcheight) / 2);
    $srcheight = floor($srcheight);
}

If you want to be absolutely sure that $srcwidth and $srcheight do not exceed the originals, you could always clamp their values.

$srcheight = min($actualsourceheight, floor($srcheight));

You could also test each scenario, as there are only a few possible variances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜