How can PHP be used to resize images for display on a website?
When displaying images on a website, it is important to resize them to ensure faster loading times and better user experience. PHP can be used to resize images by using the GD library, which provides functions for image manipulation. By using functions like imagecreatefromjpeg(), imagecopyresampled(), and imagejpeg(), you can easily resize images in PHP.
<?php
// Load the original image
$originalImage = imagecreatefromjpeg('original.jpg');
// Get the dimensions of the original image
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
// Set the desired width for the resized image
$desiredWidth = 300;
// Calculate the new height based on the desired width
$desiredHeight = ($originalHeight / $originalWidth) * $desiredWidth;
// Create a new image with the desired dimensions
$resizedImage = imagecreatetruecolor($desiredWidth, $desiredHeight);
// Resize the original image to the new dimensions
imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $originalWidth, $originalHeight);
// Output the resized image to a file or browser
imagejpeg($resizedImage, 'resized.jpg');
// Free up memory
imagedestroy($originalImage);
imagedestroy($resizedImage);
?>