Search code examples
phpimage-resizing

PHP image resize to a minimum width / height


I've been trying to figure out how to resize an uploaded image in PHP so that it is not smaller than a given size (650x650). However if a user uploads an image that is already smaller than my 650 minimum on either edge, no action is to be taken.

Scenario 1 - a 2000px width by 371px image is updloaded - this would not be resized as 371px is already less than my minimum.

Scenario 2 - a 2000px by 1823px image is uploaded - here I should resize the image as close to the minimum as possible, but not allow the width or height to be below 650px.

Here's the lines I've been thinking along so far (I'm using the excellent simpleImage script to help with resizing and getting dimensions):

$curWidth = $image->getWidth();
$curHeight = $image->getHeight();               
$ratio = $curWidth/$curHeight;

if ($curWidth>$minImageWidth && $curHeight>$minImageHeight)
{
    //both dimensions are above the minimum, so we can try scaling
    if ($curWidth==$curHeight)
    {
        //perfect square :D just resize to what we want
        $image->resize($minImageWidth,$minImageHeight);
    }
    else if ($curWidth>$curHeight)
    {
        //height is shortest, scale that.
        //work out what height to scale to that will allow 
        //width to be at least minImageWidth i.e 650.   
        if ($ratio < 1) 
        {
            $image->resizeToHeight($minImageWidth*$ratio);
        } 
        else 
        {
            $image->resizeToHeight($minImageWidth/$ratio);
        }   
    }
    else
    {
        //width is shortest, so find minimum we can scale to while keeping
        //the height above or equal to the minimum height.
        if ($ratio < 1) 
        {
            $image->resizeToWidth($minImageHeight*$ratio);
        } 
        else 
        {
            $image->resizeToWidth($minImageHeight/$ratio);
        }   
}

However this gives me some strange results, at times it will still scale below the minimum. The only part of it that works as expected is the test for the dimensions being above the minimum - it won't scale anything that's too small.

I think my biggest problem here is that I don't fully understand the relationship between the image aspect ratio and the dimensions, and how to work out what dimensions I'd be able to scale to that are above my minimums. Any suggestions?


Solution

  • try this:

    $curWidth = $image->getWidth();
    $curHeight = $image->getHeight();               
    $ratio = min($minImageWidth/$curWidth,$minImageHeight/$curHeight);
    if ($ratio < 1) {
        $image->resize(floor($ratio*$curWidth),floor($ratio*$curHeight));
    }
    

    or this:

    $image->maxarea($minImageWidth, $minImageHeight);