What are some best practices for correctly setting image dimensions in PHP scripts to avoid errors?

When working with images in PHP scripts, it is important to correctly set the dimensions to avoid errors such as distorted images or slow loading times. One best practice is to use functions like `imagesx()` and `imagesy()` to get the width and height of the image and then resize it accordingly. Additionally, always maintain the aspect ratio when resizing images to prevent distortion.

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

// Calculate the new dimensions while maintaining aspect ratio
$newWidth = 200; // Set the desired width
$newHeight = ($originalHeight / $originalWidth) * $newWidth;

// Resize the image
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);