【发布时间】:2012-02-27 14:49:34
【问题描述】:
我一直在试图弄清楚如何在 PHP 中调整上传的图片大小,使其不小于给定尺寸 (650x650)。但是,如果用户上传的图像在任一边缘上已经小于我的最小值 650,则无需采取任何措施。
场景 1 - 上传了 2000px 宽 x 371px 的图像 - 这不会调整大小,因为 371px 已经小于我的最小值。
场景 2 - 上传了 2000 像素 x 1823 像素的图片 - 这里我应该将图片的大小调整到尽可能接近最小值,但不允许宽度或高度低于 650 像素。
到目前为止,这是我一直在思考的思路(我正在使用出色的 simpleImage 脚本来帮助调整大小和获取尺寸):
$curWidth = $image->getWidth();
$curHeight = $image->getHeight();
$ratio = $curWidth/$curHeight;
if ($curWidth>$minImageWidth && $curHeight>$minImageHeight)
{
//both dimensions are above the minimum, so we can try scaling
if ($curWidth==$curHeight)
{
//perfect square :D just resize to what we want
$image->resize($minImageWidth,$minImageHeight);
}
else if ($curWidth>$curHeight)
{
//height is shortest, scale that.
//work out what height to scale to that will allow
//width to be at least minImageWidth i.e 650.
if ($ratio < 1)
{
$image->resizeToHeight($minImageWidth*$ratio);
}
else
{
$image->resizeToHeight($minImageWidth/$ratio);
}
}
else
{
//width is shortest, so find minimum we can scale to while keeping
//the height above or equal to the minimum height.
if ($ratio < 1)
{
$image->resizeToWidth($minImageHeight*$ratio);
}
else
{
$image->resizeToWidth($minImageHeight/$ratio);
}
}
但是,这给了我一些奇怪的结果,有时它仍会低于最小值。它唯一能按预期工作的部分是测试尺寸是否高于最小值 - 它不会缩放任何太小的东西。
我认为我最大的问题是我不完全理解图像纵横比和尺寸之间的关系,以及如何计算出我能够缩放到的尺寸高于我的最小值。有什么建议吗?
【问题讨论】:
-
我对前几句话感到困惑。 “宽度和高度不小于设置的最小值”......然后它说2000x371不会调整大小,因为它太短了。你能澄清你需要的规则吗?或者我误会你了。
-
我会更新以使其更清晰 - 基本上我想将某些东西重新缩放到 650 的最小宽度和高度。两者都不应该更小 - 但是如果有人上传的图像已经更小,则不应采取任何措施。
标签: php image-resizing