PHP图像裁剪问题

时间:2015-07-11 20:18:49

标签: php image crop

我有一种方法可以裁剪图像,但它保持比例,有时会给我一个长方形的图像。有没有一种方法可以固定宽度和高度,同时不会使图像偏斜或变暗?即。120px x 120px

有关如何修改此方法的任何想法吗?

注意: 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);
}

1 个答案:

答案 0 :(得分: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;
}