2015-07-11 173 views
6

我有一种方法会裁剪图像,但它保持比例,有时会给我一个长方形的图像。有没有办法让它固定宽度和高度,同时不偏斜或歪曲图像?即,120px x 120pxPHP图像裁剪问题

有关如何修改此方法来做到这一点的任何想法?

注意: maxSize设置为120px。另外,我从原始图像中传递宽度和高度。

protected function calculateSize($width, $height) { 
    if ($width <= $this->maxSize && $height <= $this->maxSize) { 
     $ratio = 1; 
    } elseif ($width > $height) { 
     $ratio = $this->maxSize/$width; 
    } else { 
     $ratio = $this->maxSize/$height; 
    } 

    $this->newWidth = round($width * $ratio); 
    $this->newHeight = round($height * $ratio); 
} 
+0

啊......所以,你要在同一时间有一个长方形和方形的裁剪图像_? – 2015-07-11 20:29:01

+0

@HoboSapiens 不,这种方法将返回一个椭圆形的图像,如果我通过它的图像是320 x 200或类似的东西。我希望它能够以固定的宽度和高度(120 x 120)均匀裁剪图像。 –

+0

@HoboSapiens, 我已更新我的问题。我知道这可能会让人困惑。 –

回答

1

假设你总是想方维回来了,这个倍增是不是一种选择,这样的事情应该工作(除非我失去了一些东西):

protected function calculateSize($width, $height) { 
    if ($height <= $this->maxSize && $width <= $this->maxSize) { 
    $new_height = $new_width = min(array($height, $width)); 
    } 
    else { 
    if ($height > $width) { 
     $variable = 'width'; 
    } 
    else { 
     $variable = 'height'; 
    } 
    if ($$variable <= $this->maxSize) { 
     $new_height = $new_width = $$variable; 
    } 
    else { 
     $new_height = $new_width = min(array($this->maxSize, $$variable)); 
    } 
    } 
    $this->newWidth = $new_width; 
    $this->newHeight = $new_height; 
}