What are the potential pitfalls of creating thumbnails in PHP, especially in terms of maintaining aspect ratios?
When creating thumbnails in PHP, one potential pitfall is maintaining the aspect ratio of the original image. If the aspect ratio is not preserved, the thumbnail may appear stretched or distorted. One way to solve this issue is to calculate the appropriate dimensions for the thumbnail while maintaining the aspect ratio of the original image.
// Calculate thumbnail dimensions while maintaining aspect ratio
function createThumbnail($source, $destination, $width, $height) {
list($sourceWidth, $sourceHeight) = getimagesize($source);
$sourceAspectRatio = $sourceWidth / $sourceHeight;
if ($width / $height > $sourceAspectRatio) {
$width = $height * $sourceAspectRatio;
} else {
$height = $width / $sourceAspectRatio;
}
$thumb = imagecreatetruecolor($width, $height);
$sourceImage = imagecreatefromjpeg($source);
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $width, $height, $sourceWidth, $sourceHeight);
imagejpeg($thumb, $destination);
}