What are the best practices for handling image resizing and white background addition in PHP for thumbnail generation?

When handling image resizing and adding a white background for thumbnail generation in PHP, it is important to use a library like GD or Imagick for image manipulation. To resize an image while maintaining its aspect ratio, you can calculate the new dimensions based on the desired thumbnail size. To add a white background, you can create a new image with the desired dimensions and fill it with a white color before overlaying the resized image on top.

// Load the original image
$originalImage = imagecreatefromjpeg('original.jpg');

// Calculate the new dimensions for the thumbnail
$thumbnailWidth = 100;
$thumbnailHeight = 100;
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
$aspectRatio = $originalWidth / $originalHeight;
if ($thumbnailWidth / $thumbnailHeight > $aspectRatio) {
    $newWidth = $thumbnailHeight * $aspectRatio;
    $newHeight = $thumbnailHeight;
} else {
    $newWidth = $thumbnailWidth;
    $newHeight = $thumbnailWidth / $aspectRatio;
}

// Create a new image with white background
$thumbnailImage = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
$white = imagecolorallocate($thumbnailImage, 255, 255, 255);
imagefill($thumbnailImage, 0, 0, $white);

// Resize and overlay the original image onto the thumbnail
imagecopyresampled($thumbnailImage, $originalImage, ($thumbnailWidth - $newWidth) / 2, ($thumbnailHeight - $newHeight) / 2, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

// Save the thumbnail image
imagejpeg($thumbnailImage, 'thumbnail.jpg');

// Free up memory
imagedestroy($originalImage);
imagedestroy($thumbnailImage);