What are some common pitfalls when trying to resize images in PHP?

One common pitfall when resizing images in PHP is not maintaining the aspect ratio, which can result in distorted images. To solve this, you can calculate the aspect ratio of the original image and then use it to resize the image proportionally.

// Load the original image
$originalImage = imagecreatefromjpeg('original.jpg');

// Get the dimensions of the original image
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);

// Calculate the aspect ratio
$aspectRatio = $originalWidth / $originalHeight;

// Set the desired width for the resized image
$desiredWidth = 300;

// Calculate the new height based on the aspect ratio
$desiredHeight = $desiredWidth / $aspectRatio;

// Create a new image with the desired dimensions
$resizedImage = imagecreatetruecolor($desiredWidth, $desiredHeight);

// Resize the original image to fit the new dimensions
imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $originalWidth, $originalHeight);

// Save the resized image
imagejpeg($resizedImage, 'resized.jpg');

// Free up memory
imagedestroy($originalImage);
imagedestroy($resizedImage);