How can the image resizing function be optimized to handle larger images efficiently in PHP?

When resizing larger images in PHP, the memory usage can increase significantly, potentially causing performance issues or even script timeouts. To optimize the image resizing function for larger images, you can use the imagecopyresampled() function instead of imagecopyresized(). imagecopyresampled() produces higher quality resized images and uses less memory, making it more efficient for handling larger images.

// Function to resize image using imagecopyresampled()
function resize_image($source_image_path, $dest_image_path, $new_width, $new_height) {
    list($source_width, $source_height) = getimagesize($source_image_path);
    $source_image = imagecreatefromjpeg($source_image_path);
    $dest_image = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
    imagejpeg($dest_image, $dest_image_path);
    imagedestroy($source_image);
    imagedestroy($dest_image);
}

// Example usage
resize_image('input.jpg', 'output.jpg', 800, 600);