What are the benefits of maintaining image proportions when resizing thumbnails in PHP and how can this be achieved?

When resizing thumbnails in PHP, maintaining image proportions is important to prevent distortion and ensure the image looks natural. This can be achieved by calculating the aspect ratio of the original image and using it to resize the thumbnail proportionally.

// Get the original image dimensions
list($width, $height) = getimagesize($original_image);

// Calculate the aspect ratio
$aspect_ratio = $width / $height;

// Set the desired thumbnail width
$thumb_width = 100;

// Calculate the thumbnail height based on the aspect ratio
$thumb_height = $thumb_width / $aspect_ratio;

// Create a new image resource for the thumbnail
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);

// Resize and copy the original image to the thumbnail
imagecopyresampled($thumb, $original_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);

// Save or display the thumbnail image
imagejpeg($thumb, 'thumbnail.jpg');