What are some potential pitfalls when resizing images in PHP, especially when dealing with different aspect ratios?

When resizing images in PHP, one potential pitfall when dealing with different aspect ratios is distortion or stretching of the image. To solve this issue, you can calculate the aspect ratio of the original image and then resize the image while maintaining the same aspect ratio to avoid distortion.

// Calculate aspect ratio of original image
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
$aspectRatio = $originalWidth / $originalHeight;

// Resize image while maintaining aspect ratio
$newWidth = 500; // new width
$newHeight = $newWidth / $aspectRatio; // calculate new height based on aspect ratio

$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);