Skip to content
PHP Logo

In what ways can PHP developers optimize their code for efficiency when resizing images dynamically on a website?

When resizing images dynamically on a website, PHP developers can optimize their code for efficiency by using the GD library functions, caching resized images to reduce server load, and ensuring proper image formats and compression levels are used.

php
// Example PHP code snippet for resizing images using GD library functions

function resize_image($source_image_path, $new_image_path, $new_width, $new_height) {
    list($source_width, $source_height) = getimagesize($source_image_path);
    $source_image = imagecreatefromjpeg($source_image_path);
    $new_image = imagecreatetruecolor($new_width, $new_height);
    
    imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
    
    imagejpeg($new_image, $new_image_path, 90); // 90 is the image quality (0-100)
    
    imagedestroy($source_image);
    imagedestroy($new_image);
}

// Usage example
resize_image('original.jpg', 'resized.jpg', 300, 200);