How can you optimize image processing in PHP to avoid overwriting the original image during scaling?
When scaling images in PHP, you can avoid overwriting the original image by saving the scaled image with a different filename or in a different directory. This way, you preserve the original image while still having the scaled version available for use.
// Load the original image
$original_image = imagecreatefromjpeg('original.jpg');
// Scale the image to a new size
$width = imagesx($original_image) * 0.5;
$height = imagesy($original_image) * 0.5;
$scaled_image = imagescale($original_image, $width, $height);
// Save the scaled image with a new filename
imagejpeg($scaled_image, 'scaled_image.jpg');
// Free up memory
imagedestroy($original_image);
imagedestroy($scaled_image);