Skip to content

Instantly share code, notes, and snippets.

@paulund
Last active November 5, 2021 10:33
Show Gist options
  • Save paulund/5244517 to your computer and use it in GitHub Desktop.
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.
<?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;
}
?>
@Joe-abdo
Copy link

thanks m8, really helped me out :)

@hikmatkmatz
Copy link

ok

@TI360Dev
Copy link

TI360Dev commented Nov 3, 2021

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

@TI360Dev
Copy link

TI360Dev commented Nov 5, 2021

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