Are there any best practices for handling image resizing in PHP?
When resizing images in PHP, it is important to maintain the aspect ratio to prevent distortion. One common approach is to calculate the new dimensions based on a desired width or height while preserving the original aspect ratio. This can be achieved by determining the scaling factor and applying it to both dimensions.
function resizeImage($source, $destination, $maxWidth, $maxHeight) {
list($width, $height) = getimagesize($source);
$ratio = $width / $height;
if ($maxWidth / $maxHeight > $ratio) {
$maxWidth = $maxHeight * $ratio;
} else {
$maxHeight = $maxWidth / $ratio;
}
$image = imagecreatetruecolor($maxWidth, $maxHeight);
$sourceImage = imagecreatefromjpeg($source);
imagecopyresampled($image, $sourceImage, 0, 0, 0, 0, $maxWidth, $maxHeight, $width, $height);
imagejpeg($image, $destination, 100);
}