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);
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With