How can PHP scripts be modified to maintain the aspect ratio of uploaded images while resizing them?
When resizing images in PHP, it's important to maintain the aspect ratio to prevent distortion. One way to achieve this is by calculating the new dimensions based on the original aspect ratio before resizing the image.
// Get the uploaded image file
$image = imagecreatefromjpeg('uploaded_image.jpg');
// Set the desired width and calculate the new height to maintain aspect ratio
$desired_width = 300;
$original_width = imagesx($image);
$original_height = imagesy($image);
$desired_height = floor($original_height * ($desired_width / $original_width));
// Create a new image with the calculated dimensions
$new_image = imagecreatetruecolor($desired_width, $desired_height);
// Resize the original image to fit the new dimensions
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $desired_width, $desired_height, $original_width, $original_height);
// Save or output the resized image
imagejpeg($new_image, 'resized_image.jpg');
// Free up memory
imagedestroy($image);
imagedestroy($new_image);