这个调整图像大小/裁剪图像的逻辑是不是正确(在 php 中,但它是关于逻辑而不是代码)
Posted
技术标签:
【中文标题】这个调整图像大小/裁剪图像的逻辑是不是正确(在 php 中,但它是关于逻辑而不是代码)【英文标题】:Is this logic for resizing/cropping images correct (in php but it's about the logic rather than the code)这个调整图像大小/裁剪图像的逻辑是否正确(在 php 中,但它是关于逻辑而不是代码) 【发布时间】:2011-02-01 15:31:31 【问题描述】:大家好,我有一个 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
),然后可以将其传递到 @987654326 @。
我想检查的主要内容是比率检查将防止$srcheight
和$srcwidth
大于原始宽度/高度,因为这会破坏它,但我认为不会?
非常感谢大家!
戴夫
【问题讨论】:
【参考方案1】:它似乎工作。我会对其进行一些重构,初始化变量并提取它们。这消除了对最后一个 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));
您也可以测试每个场景,因为只有少数可能的差异。
【讨论】:
感谢您的回答,我同意初始化变量。我已经用多种差异对其进行了测试,它总是能很好地返回,但是我真的只是想从数学上检查我是否正确地认为无论宽度/高度是多少,这些都永远不会被超过?以上是关于这个调整图像大小/裁剪图像的逻辑是不是正确(在 php 中,但它是关于逻辑而不是代码)的主要内容,如果未能解决你的问题,请参考以下文章