Type Here to Get Search Results !
×
Hi ,

We always try to serve you better. Please enter the institute name, you belong to.

×
Hello ,

Your daily download limit has been exhausted. Share it with your friends to download more.

How to deliver images with size parameter in url in php and htaccess

 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

Note that you should sanitize and validate the filename and size parameter to prevent security issues and unexpected behavior.

Add following code in htaccess to rewrite:

RewriteEngine On
RewriteRule ^images/(/?.*)$ images/image.php?filename=$1 [NC,L,QSA]


That's all. If you have any issue. Please let me know in the comment section.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.