【问题标题】:PHP Image Crop IssuePHP 图像裁剪问题
【发布时间】:2015-09-30 10:07:55
【问题描述】:

我有一种方法可以裁剪图像,但它会保持比例,有时会给我一个长方形的图像。有没有办法在不歪斜或扭曲图像的情况下固定宽度和高度?即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);
}

【问题讨论】:

  • 啊...所以你想要一个同时长方形和正方形的裁剪图像
  • @HoboSapiens 不,如果我向它传递一个 320 x 200 或类似的图像,此方法将返回一个长方形图像。我希望它返回一个以固定宽度和高度(如 120 x 120)均匀裁剪的图像。
  • @HoboSapiens,我已经更新了我的问题。我知道这会让人感到困惑。

标签: php image crop


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 2019-10-23
    • 2014-04-05
    相关资源
    最近更新 更多