What is the purpose of using imagecopyresized in PHP for image processing?

When working with images in PHP, you may need to resize an image to a specific width and height while maintaining its aspect ratio. The imagecopyresized function in PHP allows you to resize an image and create a new image with the desired dimensions.

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

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

// Set the desired width and height for the resized image
$desired_width = 300;
$desired_height = 200;

// Create a new image with the desired dimensions
$resized_image = imagecreatetruecolor($desired_width, $desired_height);

// Resize the original image to fit the new dimensions
imagecopyresized($resized_image, $original_image, 0, 0, 0, 0, $desired_width, $desired_height, $original_width, $original_height);

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

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