How can PHP be used to resize images to a specific size while maintaining proportions?
When resizing images in PHP, it is important to maintain the original aspect ratio to avoid distortion. One way to achieve this is by calculating the new dimensions based on the desired width or height while preserving the original proportions. This can be done by determining the scaling factor and then applying it to both dimensions.
function resize_image($source_image_path, $new_image_path, $desired_width, $desired_height) {
list($source_width, $source_height) = getimagesize($source_image_path);
$source_aspect_ratio = $source_width / $source_height;
$desired_aspect_ratio = $desired_width / $desired_height;
if ($source_aspect_ratio > $desired_aspect_ratio) {
$new_width = $desired_width;
$new_height = $desired_width / $source_aspect_ratio;
} else {
$new_height = $desired_height;
$new_width = $desired_height * $source_aspect_ratio;
}
$source_image = imagecreatefromjpeg($source_image_path);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
imagejpeg($new_image, $new_image_path);
}