To deliver images with a size parameter in the URL on a PHP website, you can use PHP's GD library to resize the image dynamically based on the size parameter in the URL.
Here's an example code that does this:
// Get the requested image filename from the URL
$filename = $_GET['filename'];
// Get the requested size parameter from the URL
$size = isset($_GET['size']) ? $_GET['size'] : 200;
// Load the original image from a file
$originalImage = imagecreatefromjpeg($filename);
// Get the original dimensions of the image
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
// Calculate the new dimensions based on the requested size parameter
if ($originalWidth > $originalHeight) {
$newWidth = $size;
$newHeight = round($originalHeight * ($size / $originalWidth));
} else {
$newWidth = round($originalWidth * ($size / $originalHeight));
$newHeight = $size;
}
// Create a new image with the new dimensions
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// Copy and resize the original image to the new image
imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
// Output the new image to the browser as a JPEG
header('Content-Type: image/jpeg');
imagejpeg($newImage);
// Free up memory
imagedestroy($originalImage);
imagedestroy($newImage);
This code uses $_GET to get the requested image filename and size parameter from the URL. It loads the original image using imagecreatefromjpeg(), calculates the new dimensions based on the requested size parameter, creates a new image with the new dimensions using imagecreatetruecolor(), copies and resizes the original image to the new image using imagecopyresampled(), outputs the new image to the browser as a JPEG using header() and imagejpeg(), and frees up memory using imagedestroy().
To use this code, you can include it in a PHP file and link to the file with the image filename and size parameter in the URL. For example, if the PHP file is named image.php and you want to display an image named example.jpg at a size of 300 pixels, you can use the following URL:
http://example.com/image.php?filename=example.jpg&size=300
RewriteEngine OnRewriteRule ^images/(/?.*)$ images/image.php?filename=$1 [NC,L,QSA]
Post a Comment
0 Comments