How can PHP functions like imagecreatefromjpeg be used to handle image processing, and what are common pitfalls when dealing with large image files?

When handling image processing in PHP, functions like imagecreatefromjpeg can be used to create an image resource from a JPEG file. However, when dealing with large image files, common pitfalls include memory exhaustion and slow processing times. To mitigate these issues, it is important to properly handle memory allocation and consider using techniques like image resizing or lazy loading.

// Example code snippet for handling large image files in PHP
$filename = 'large_image.jpg';

// Check image dimensions before processing
list($width, $height) = getimagesize($filename);

// Resize large images to a manageable size
$max_width = 800;
$max_height = 600;

if ($width > $max_width || $height > $max_height) {
    $ratio = $width / $height;

    if ($width > $height) {
        $new_width = $max_width;
        $new_height = $max_width / $ratio;
    } else {
        $new_height = $max_height;
        $new_width = $max_height * $ratio;
    }

    $image = imagecreatefromjpeg($filename);
    $resized_image = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($resized_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

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

    // Free up memory
    imagedestroy($image);
    imagedestroy($resized_image);
} else {
    // Process the image as usual
    $image = imagecreatefromjpeg($filename);
    // Add your image processing code here
    // Don't forget to free up memory when done
    imagedestroy($image);
}