How can the GD library be utilized for image resizing in PHP?

To utilize the GD library for image resizing in PHP, you can use the imagecopyresampled function to resize an image while maintaining its aspect ratio. This function allows you to specify the destination width and height for the resized image.

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

// Get the original image dimensions
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);

// Calculate the new dimensions for the resized image
$newWidth = 300; // New width for the resized image
$newHeight = ($originalHeight / $originalWidth) * $newWidth;

// Create a new image with the new dimensions
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);

// Resize the original image to the new dimensions
imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

// Save the resized image to a new file
imagejpeg($resizedImage, 'resized.jpg');

// Free up memory
imagedestroy($originalImage);
imagedestroy($resizedImage);