Last active
November 5, 2021 10:33
-
-
Save paulund/5244517 to your computer and use it in GitHub Desktop.
Resize a image to a max width and height and keep aspect ratio.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function getImageSizeKeepAspectRatio( $imageUrl, $maxWidth, $maxHeight) | |
{ | |
$imageDimensions = getimagesize($imageUrl); | |
$imageWidth = $imageDimensions[0]; | |
$imageHeight = $imageDimensions[1]; | |
$imageSize['width'] = $imageWidth; | |
$imageSize['height'] = $imageHeight; | |
if($imageWidth > $maxWidth || $imageHeight > $maxHeight) | |
{ | |
if ( $imageWidth > $imageHeight ) { | |
$imageSize['height'] = floor(($imageHeight/$imageWidth)*$maxWidth); | |
$imageSize['width'] = $maxWidth; | |
} else { | |
$imageSize['width'] = floor(($imageWidth/$imageHeight)*$maxHeight); | |
$imageSize['height'] = $maxHeight; | |
} | |
} | |
return $imageSize; | |
} | |
?> |
ok
Hi,
thanks for this function, i'm working with it but i think that i found a bug.... for example:
getImageSizeKeepAspectRatio( $imageUrl, 450, 690) with a image 516x687, the bug its that in the if ( $imageWidth > $imageHeight ) don't acomplish this and It don't make nothing with width. I'm working on it.
Thanks
Hi,
I think that fix the bug.....
function getImageSizeKeepAspectRatio( $imageUrl, $maxWidth, $maxHeight){
$imageDimensions = getimagesize($imageUrl);
$imageWidth = $imageDimensions[0];
$imageHeight = $imageDimensions[1];
$imageSize['width'] = $imageWidth;
$imageSize['height'] = $imageHeight;
if ($imageWidth > $imageHeight) {
if($imageWidth < $maxWidth)
$newwidth = $imageWidth;
else
$newwidth = $maxWidth;
$divisor = $imageWidth / $newwidth;
$newheight = floor( $imageHeight / $divisor);
}
else {
if($imageHeight < $maxHeight)
$newheight = $imageHeight;
else
$newheight = $maxHeight;
$divisor = $imageHeight / $newheight;
$newwidth = floor( $imageWidth / $divisor );
/* New code */
if ($newwidth>$maxWidth){
$newwidth = $maxWidth;
$divisor = $imageWidth / $newwidth;
$newheight = floor( $imageHeight / $divisor);
}
}
$imageSize['width'] = $newwidth;
$imageSize['height'] = $newheight;
return $imageSize;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks m8, really helped me out :)