2011-02-01 122 views
0

嘿大家好,我有一个PHP脚本来调整图像大小,如果方面是相同的,它只是调整大小他们,但如果它不同,它会先收获它们。我只是想检查我的逻辑是正确的,这将计算相关尺寸的所有源和目标图像大小:这是逻辑大小/裁剪图像正确(在PHP中,但它是关于逻辑,而不是代码)

$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; 
} 

从我可以出这应该抓住一切可能发生的与生产开始x,y坐标($srcx$srcy)和源尺寸($srcwidth,$srcheight),然后可以将其传递到imagecopyresampled

我想检查的主要原因是比率检查会阻止$srcheight$srcwidth从原始宽度/高度大于原始宽度/高度,因为这会破坏它,但我不认为它会?

非常感谢大家!

戴夫

回答

0

它似乎工作。我会重构一些,初始化变量并提取它们。这消除了对最后的else块的需求,并使代码更清晰。

$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); 
} 

如果你想绝对确保$srcwidth$srcheight不超过原稿,你总是可以钳制它们的值。

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

您也可以测试每种情况,因为只有少数可能的差异。

+0

感谢您的回答,我同意初始化变量。我已经测试了多个差异,它总是回来很好,但我真的只是想检查数学,我认为这些将永远不会超过无论宽度/高度是多少? – deshg 2011-02-15 18:22:11