Are there any best practices for scaling and resizing images in PHP for thumbnail creation?

When creating thumbnails in PHP, it is important to scale and resize images efficiently to maintain image quality and reduce file size. One common approach is to use the GD library functions in PHP to resize images while preserving aspect ratio. By calculating the new dimensions based on the desired thumbnail size, you can create high-quality thumbnails for your website or application.

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

// Get the original dimensions
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);

// Calculate the new dimensions for the thumbnail
$thumbnail_width = 100;
$thumbnail_height = floor($original_height * ($thumbnail_width / $original_width));

// Create a new image with the thumbnail dimensions
$thumbnail_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);

// Resize the original image to fit the thumbnail dimensions
imagecopyresampled($thumbnail_image, $original_image, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $original_width, $original_height);

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

// Free up memory
imagedestroy($original_image);
imagedestroy($thumbnail_image);