What are the best practices for optimizing image size retrieval in PHP scripts to minimize script runtime and improve performance?

When retrieving images in PHP scripts, it's important to optimize the image size to minimize script runtime and improve performance. One way to achieve this is by resizing images before displaying them on the webpage. This can be done using PHP's GD or Imagick extension to resize the image to the desired dimensions.

// Example code to resize and display an image using PHP GD extension
$source_image = 'path/to/source/image.jpg';
$target_width = 300;
$target_height = 200;

list($source_width, $source_height) = getimagesize($source_image);

$source = imagecreatefromjpeg($source_image);
$target = imagecreatetruecolor($target_width, $target_height);

imagecopyresampled($target, $source, 0, 0, 0, 0, $target_width, $target_height, $source_width, $source_height);

header('Content-Type: image/jpeg');
imagejpeg($target);
imagedestroy($source);
imagedestroy($target);