0

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

Community
  • 1
  • 1
Purus
  • 5,701
  • 9
  • 50
  • 89
  • Why is this down-voted? plz do explain if anything is not clear. I am not an expert. – Purus Oct 19 '13 at 18:57
  • I don't understand the problem. From the doc: "By default, resizing keeps the original image’s aspect ratio and the resulting image fits the given dimensions from the inside." So $img->resize(200,200) should be enough. – user276648 Feb 18 '14 at 07:42
  • No. It won't as you say. – Purus Feb 18 '14 at 08:55
  • I'm just using `WideImage::load($img)->resizeDown(1024,768)->saveToFile($filename)` and all my images (that can have different aspect ratio, be in portrait or landscape) still keep their aspect ratio. – user276648 Feb 19 '14 at 03:02

1 Answers1

1

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)
Purus
  • 5,701
  • 9
  • 50
  • 89