What are common methods to resize images in PHP while maintaining proportions?
When resizing images in PHP, it is important to maintain the original proportions to prevent distortion. One common method to achieve this is by calculating the aspect ratio of the original image and then resizing it accordingly.
function resize_image($image_path, $new_width, $new_height) {
list($width, $height) = getimagesize($image_path);
$original_aspect = $width / $height;
$new_aspect = $new_width / $new_height;
if ($original_aspect >= $new_aspect) {
$final_width = $new_width;
$final_height = $new_width / $original_aspect;
} else {
$final_height = $new_height;
$final_width = $new_height * $original_aspect;
}
$image = imagecreatetruecolor($final_width, $final_height);
$original_image = imagecreatefromjpeg($image_path);
imagecopyresampled($image, $original_image, 0, 0, 0, 0, $final_width, $final_height, $width, $height);
return $image;
}