Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Image Crop Issue

Tags:

php

image

crop

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);
}
like image 495
Houston Molinar Avatar asked Jul 11 '15 20:07

Houston Molinar


1 Answers

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;
}
like image 171
jerdiggity Avatar answered Nov 10 '22 00:11

jerdiggity