What are the best practices for adjusting the height of images in PHP while maintaining aspect ratio?
When adjusting the height of images in PHP while maintaining aspect ratio, it is important to calculate the new width based on the aspect ratio to prevent distortion. One common approach is to calculate the aspect ratio of the original image and then use it to determine the new width when adjusting the height.
// Set the desired height
$newHeight = 300;
// Load the original image
$originalImage = imagecreatefromjpeg('original.jpg');
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
// Calculate the aspect ratio
$aspectRatio = $originalWidth / $originalHeight;
// Calculate the new width based on the aspect ratio
$newWidth = $newHeight * $aspectRatio;
// Create a new image with the adjusted dimensions
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
// Save or output the new image
imagejpeg($newImage, 'adjusted.jpg');
// Free up memory
imagedestroy($originalImage);
imagedestroy($newImage);