PHP图像调整为最小宽度/高度

时间:2012-02-27 14:49:34

标签: php image-resizing

我一直在试图弄清楚如何在PHP中调整上传图像的大小,使其不小于给定大小(650x650)。但是,如果用户在任一边缘上传的图像已经小于我的650最小值,则不会采取任何措施。

场景1 - 一个2000px宽度乘以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);
        }   
}

然而,这给了我一些奇怪的结果,有时它仍然会低于最小值。其中唯一能够按预期工作的部分是尺寸高于最小尺寸的测试 - 它不会扩展任何太小的尺寸。

我认为我最大的问题是我不完全理解图像宽高比和尺寸之间的关系,以及如何计算出我能够扩展到哪个尺寸超出我的最小值。有什么建议吗?

3 个答案:

答案 0 :(得分:4)

试试这个:

$curWidth = $image->getWidth();
$curHeight = $image->getHeight();               
$ratio = min($minImageWidth/$curWidth,$minImageHeight/$curHeight);
if ($ratio < 1) {
    $image->resize(floor($ratio*$curWidth),floor($ratio*$curHeight));
}

或者这个:

$image->maxarea($minImageWidth, $minImageHeight);

答案 1 :(得分:2)

试试这个:

$curWidth  = $image->getWidth();
$curHeight = $image->getHeight();               
if ($curWidth>$minImageWidth && $curHeight>$minImageHeight) {
   $ratio = $curWidth/$curHeight;
   $zoom = image_ratio > 1
         ? $minImageHeight / $curHeight
         : $minImageWidth / $curWidth
         ;

   $newWidth = $curWidth * $zoom;
   $newHeight = $curHeight * $zoom;
}

答案 2 :(得分:0)

通用代码段会计算图片的最小尺寸,但前提是这两个尺寸都大于最小尺寸。

$min_height/$min_width

该算法将最小尺寸比($height/$width)与当前图像尺寸比($min_height)进行比较。

  1. 如果当前图像比率较大,则需要缩放图像,使高度等于$ratio = $height/$min_height。设置$min_width
  2. 如果当前图像比率较小,则需要缩放图像,使宽度等于$ratio = $width/$min_width。设置$ratio
  3. 要获得正确的尺寸,请将宽度和高度乘以$new_width = $width * $ratio; $new_height = $height * $ratio;

    {{1}}