• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

PHP How to resize an image with fixed height but auto size the width in PHP?

Roy Harper

New Coder
I created a function that resize an image. But I only want to define the target height and then auto size the width.
For example if I have a 840x360. My target height is 250 and I want to auto compute the width to maintain it's ratio.
So far I can only resize the image based on the resolution provided. The code is working fine, I just can't figure out the right computation to achieve it.

Resizing image:
$image = $_FILES['image']['tmp_name'];

// Define the target resolution
$max_resolution = 500;

// Get original dimensions
$size = getimagesize($image);
$original_width = $size[0];
$original_height = $size[1];

// Resize image
$ratio = $max_resolution / $original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;

if($new_height > $max_resolution){
    $ratio = $max_resolution / $original_height;
    $new_height = $max_resolution;
    $new_width = $original_width * $ratio;
}

// Open original image
$original = imagecreatefromjpeg($image);
$resized = imagecreatetruecolor($new_width, $new_height);

imagecopyresampled(
    $resized, $original,
    0,0,0,0,
    $new_width, $new_height,
    $original_width, $original_height
);

imagewebp($resized, "image/thumb/resized.webp");

echo "Resized!";

imagedestroy($original);
imagedestroy($resized);
 
Solution
Never mind, I have already solved it using this formula:

$new_heigth = 300;

PHP:
// Resize image
$new_heigth = 300;

$ratio = $original_width / $original_height;
$new_width = ceil($ratio * $new_height);

Roy Harper

New Coder
Never mind, I have already solved it using this formula:

$new_heigth = 300;

PHP:
// Resize image
$new_heigth = 300;

$ratio = $original_width / $original_height;
$new_width = ceil($ratio * $new_height);
 
Solution

Ghost

Active Coder
Never mind, I have already solved it using this formula:

$new_heigth = 300;

PHP:
// Resize image
$new_heigth = 300;

$ratio = $original_width / $original_height;
$new_width = ceil($ratio * $new_height);
Glad you sorted it out. If you need further help, you can check out some of my image tools on Github. They're coded in Python, but the logic & math is the same so it can be easily converted to PHP:

Bulk Photo Trim - https://github.com/NerdiOrg/bulk-photo-trim
Smart Crop Size - https://github.com/NerdiOrg/smart-crop-size
Bulk Image Brand - https://github.com/NerdiOrg/bulk-image-brand
 

Top