Houston Molinar
Houston Molinar

Reputation: 191

PHP Image Crop Issue

I have a method that will crop an image but it maintains ratio and sometimes gives me an oblong image. Is there a way have it fixed width and height while not skewing or distoring the image? ie., 120px x 120px?

Any ideas on how to modify this method to do that?

Note: maxSize is set to 120px. Additionally, I'm passing in the width and height from the original image.

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);
}

Upvotes: 6

Views: 179

Answers (1)

jerdiggity
jerdiggity

Reputation: 3675

Assuming you always want square dimensions returned, and that upscaling is not an option, something like this should work (unless I'm missing something):

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;
}

Upvotes: 1

Related Questions