Search code examples
phpimageheightwidth

how to resize an image while maintaining width and height ratio


I am using this function to resize an uploaded image:

function imageResize($imageResourceId,$width,$height) {

    $targetWidth =750;
    $targetHeight =300;

    $targetLayer = imagecreatetruecolor($targetWidth,$targetHeight);
    imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);

    return $targetLayer;
}

But this makes the image 750 width and 300 height. The height should be flexible and depends on the width. So i am looking for something like this:

 $targetWidth = 750;
 $targetHeight = auto;

i really do not know how i should do this...


Solution

  • You can easily calculate the ratio of the original image and apply it to the resized one:

    $targetHeight = ($height / $width) * $targetWidth