What are best practices for dynamically resizing images in PHP based on specific conditions or requirements?

When dynamically resizing images in PHP based on specific conditions or requirements, it is important to maintain the aspect ratio of the image to prevent distortion. One common approach is to use the GD library in PHP to resize images while preserving their aspect ratio. By calculating the new dimensions based on the desired size and aspect ratio, you can dynamically resize images in PHP.

// Load the original image
$original_image = imagecreatefromjpeg('original.jpg');

// Define the desired width and height
$desired_width = 300;
$desired_height = 200;

// Get the original dimensions
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);

// Calculate the new dimensions while preserving aspect ratio
if ($original_width > $original_height) {
    $new_width = $desired_width;
    $new_height = floor($original_height * ($desired_width / $original_width));
} else {
    $new_height = $desired_height;
    $new_width = floor($original_width * ($desired_height / $original_height));
}

// Create a new image with the resized dimensions
$resized_image = imagecreatetruecolor($new_width, $new_height);

// Resize the original image to the new dimensions
imagecopyresampled($resized_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

// Output the resized image
imagejpeg($resized_image, 'resized.jpg');

// Free up memory
imagedestroy($original_image);
imagedestroy($resized_image);