Skip to content
PHP Logo

How can PHP scripts be structured to efficiently resize and display images without altering the original files?

To efficiently resize and display images without altering the original files in PHP, you can use the GD library functions to create a new image with the desired dimensions. This new image can then be displayed on the webpage without affecting the original file.

php
<?php
// 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 and height for the resized image
$new_width = 200;
$new_height = 150;

// Create a new image with the desired dimensions
$resized_image = imagecreatetruecolor($new_width, $new_height);

// Resize the original image to fit the new dimensions
imagecopyresampled($resized_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

// Output the resized image to the browser
header('Content-Type: image/jpeg');
imagejpeg($resized_image);

// Free up memory
imagedestroy($original_image);
imagedestroy($resized_image);
?>