phpimagewideimage

Keeping aspect ration when resizing images using WideImage PHP library


I am looking to resize an image to a pre-defined maximum size keeping the aspect ratio with the help of WideImage Library.

Example:

Maximum Allowed Dimesions: 200x200

Input Image Dimension: 300x200 logo (1,5:1 aspect ratio),

Current Output Image Dimension: 200x200

Expected Output Image Dimension : 200x133 (1,5:1 aspect ratio).

Currently the images are distorted as aspect ratio is changed. What should be done to keep that aspect ratio?

I am using the code found below.

$targetWidth = 200;
$targetHeight = 200;

$sourceRatio = $sourceWidth / $sourceHeight;
$targetRatio = $targetWidth / $targetHeight;

if ( $sourceRatio < $targetRatio ) {
    $scale = $sourceWidth / $targetWidth;
} else {
    $scale = $sourceHeight / $targetHeight;
}

$resizeWidth = (int)($sourceWidth / $scale);
$resizeHeight = (int)($sourceHeight / $scale);


$img->resize($resizeWidth, $resizeHeight)

PS: I got the above logic from Resize image without distortion keeping aspect ratio then crop excess using WideImage


Solution

  • This simple logic came to my help.

    $targetWidth = 200;
    $targetHeight = 200;
    
    $ratio = $srcWidth / $srcHeight;
    
    if ($ratio > 1) {
        $resizeWidth = $targetWidth;
        $resizeHeight= $targetHeight / $ratio;
    } else {
        $resizeWidth = $targetWidth * $ratio;
        $resizeHeight= $targetHeight;
    }
    
    $img->resize($resizeWidth, $resizeHeight)