phpgdphp-gd

Max crop area for a given image and aspect ratio


Is there any PHP/GD function that can calculate this:

Input: image width, image height and an aspect ratio to honor. Output: the width/height of the max centered crop that respects the given aspect ratio (despite image original aspect ratio).

Example: image is 1000x500, a.r. is 1.25: max crop is 625x500. image is 100x110, max crop is: 80x110.


Solution

  • There is no function that calculates this because it's elementary math:

    $imageWidth = 1000;
    $imageHeight = 500;
    $ar = 1.25;
    
    if ($ar < 1) { // "tall" crop
        $cropWidth = min($imageHeight * $ar, $imageWidth);
        $cropHeight = $cropWidth / $ar;
    }
    else { // "wide" or square crop
        $cropHeight = min($imageWidth / $ar, $imageHeight);
        $cropWidth = $cropHeight * $ar;
    }
    

    See it in action.