How can PHP code be optimized to ensure that images are resized without distortion?
To ensure that images are resized without distortion in PHP, it is important to maintain the aspect ratio of the image when resizing. This can be achieved by calculating the aspect ratio of the original image and then using it to resize the image proportionally. By doing this, the image will be resized without distortion.
// Load the original image
$original_image = imagecreatefromjpeg('original.jpg');
// Get the dimensions of the original image
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);
// Set the desired width for the resized image
$desired_width = 300;
// Calculate the aspect ratio
$aspect_ratio = $original_width / $original_height;
// Calculate the height based on the aspect ratio
$desired_height = $desired_width / $aspect_ratio;
// Create a new image with the desired dimensions
$resized_image = imagecreatetruecolor($desired_width, $desired_height);
// Resize the original image to the new dimensions
imagecopyresampled($resized_image, $original_image, 0, 0, 0, 0, $desired_width, $desired_height, $original_width, $original_height);
// Save the resized image
imagejpeg($resized_image, 'resized.jpg');
// Free up memory
imagedestroy($original_image);
imagedestroy($resized_image);