In PHP, what are some best practices for resizing and saving images after they have been uploaded?

When resizing and saving images after they have been uploaded, it is important to maintain image quality while reducing file size for optimal web performance. One common approach is to use the GD library in PHP to resize the image to the desired dimensions and save it in an appropriate format (such as JPEG or PNG). It is also recommended to store the resized images in a separate directory to keep the original uploads intact.

// Example code to resize and save an uploaded image using GD library

$uploadDir = 'uploads/';
$resizeDir = 'resized/';

// Get the uploaded file
$uploadedFile = $_FILES['image']['tmp_name'];

// Create an image resource from the uploaded file
$source = imagecreatefromstring(file_get_contents($uploadedFile));

// Get the dimensions of the uploaded image
$width = imagesx($source);
$height = imagesy($source);

// Set the desired dimensions for the resized image
$newWidth = 300;
$newHeight = 200;

// Create a new image resource for the resized image
$destination = imagecreatetruecolor($newWidth, $newHeight);

// Resize the image
imagecopyresampled($destination, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Save the resized image to the specified directory
$imageName = uniqid() . '.jpg'; // Generate a unique filename
imagejpeg($destination, $resizeDir . $imageName);

// Free up memory
imagedestroy($source);
imagedestroy($destination);

// Optionally, you can delete the original uploaded file
unlink($uploadedFile);