How can PHP be used to resize images for thumbnails without distortion?
When resizing images for thumbnails in PHP, it is important to maintain the aspect ratio to prevent distortion. One way to achieve this is by calculating the new dimensions based on the original image's width and height. By using functions like `imagecreatetruecolor()` and `imagecopyresampled()`, you can resize the image while preserving its proportions.
// Load the original image
$original_image = imagecreatefromjpeg('original.jpg');
// Get the original dimensions
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);
// Set the desired thumbnail width
$thumbnail_width = 100;
// Calculate the proportional height
$thumbnail_height = floor($original_height * ($thumbnail_width / $original_width));
// Create a new true color image
$thumbnail_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
// Resize the original image to the new 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);