What is the process for uploading and resizing images in PHP?

When uploading images in PHP, you may need to resize them to a specific dimension before saving them to your server. This can be achieved by using the GD library in PHP, which provides functions for image manipulation. By uploading the image, creating a new resized image, and saving it to the server, you can easily resize images in PHP.

// Set the maximum dimensions for the resized image
$maxWidth = 500;
$maxHeight = 500;

// Upload the image
$uploadedFile = $_FILES['image']['tmp_name'];

// Create a new image from the uploaded file
$source = imagecreatefromjpeg($uploadedFile);

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

// Calculate the new dimensions for the resized image
if ($width > $maxWidth || $height > $maxHeight) {
    $ratio = min($maxWidth/$width, $maxHeight/$height);
    $newWidth = $width * $ratio;
    $newHeight = $height * $ratio;
} else {
    $newWidth = $width;
    $newHeight = $height;
}

// Create a new image with the resized dimensions
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);

// Resize the original image to the new dimensions
imagecopyresampled($resizedImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Save the resized image to the server
imagejpeg($resizedImage, 'path/to/save/resized_image.jpg');

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