Roy Harper
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.
[CODE lang="php" title="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);[/CODE]
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.
[CODE lang="php" title="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);[/CODE]