How can PHP developers ensure that images maintain their original proportions while resizing?
When resizing images in PHP, developers can ensure that the images maintain their original proportions by calculating the aspect ratio of the original image and then using this ratio to resize the image proportionally in both dimensions.
<?php
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_width = $new_height * $original_aspect;
$final_height = $new_height;
}
$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;
}
?>
Related Questions
- How can PHP beginners avoid common errors when trying to display dynamic content based on current date and time?
- What are the differences in session handling between different browsers when working with PHP code that generates PDF files?
- What are the potential security risks of using file_get_contents with URLs in PHP?