How does the memory limit in PHP affect the resizing of large images, and what can be done to optimize memory usage in such cases?

When resizing large images in PHP, the memory limit can be easily exceeded, leading to errors or crashes. To optimize memory usage in such cases, you can resize the image using streams instead of loading the entire image into memory at once. This allows you to process the image in chunks, reducing the overall memory footprint.

function resizeImage($source, $destination, $newWidth, $newHeight) {
    $sourceImg = imagecreatefromstring(file_get_contents($source));
    $resizedImg = imagecreatetruecolor($newWidth, $newHeight);
    
    imagecopyresampled($resizedImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($sourceImg), imagesy($sourceImg));
    
    imagejpeg($resizedImg, $destination);
    
    imagedestroy($sourceImg);
    imagedestroy($resizedImg);
}