Php – Resize image without distortion keeping aspect ratio then crop excess using WideImage

image resizingPHP

I have an area on a site that I am working on that will display a users profile image that is pulled from an external source (therefore no control on its original size).

What I am looking to do is take an image (in this example 1000px x 800px and resize it to 200px x 150px. Obviously with this there is an aspect ratio difference.

What I want to do is resize the original image without distortion, which in this case would produce a 200px x 160px image. What I then want to do is crop any excess from the edges to produce the correct image size. So in this case crop 5px off the top and bottom of the image finally producing a 200px x 150px.

I have the WideImage library currently and would like to use that. I have seen several similar questions on SO but nothing that I can say exactly does as I am trying to achieve.

Best Answer

You might try:

$img->resize(200, 150, 'outside')->crop('center', 'middle', 200, 150);

Some users post their versions of calculations... Here's also my version:

$sourceWidth = 1000;
$sourceHeight = 250;

$targetWidth = 200;
$targetHeight = 150;

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

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

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

$cropLeft = (int)(($resizeWidth - $targetWidth) / 2);
$cropTop = (int)(($resizeHeight - $targetHeight) / 2);

var_dump($resizeWidth, $resizeHeight, $cropLeft, $cropTop);
Related Topic