Home Apache PHP Ubuntu MySQL Linux HTML Win CSS Perl Javascript Rants Retro
 
Print This Page
Date Posted: Saturday 06th of March 2010 | Category: PHP
Dynamically resize images in PHP.
You may be running your own online gallery. When your dealing with lots of photos, it becomes a pain having to upload the main image and thumbnail.

It would be good if you could enter the URL of the main image and have this dynamically resized.

Below is .php script which dynamically resizes any image.
Copy and paste this code in to a new .php doc and save it as thumbnail.php

<?php

$imageSrc = (string)['image'];
$width =['width'];

if (is_numeric($width) && isset($imageSrc)){
header('Content-type: image/jpeg');
makeThumb($imageSrc, $width);
}

function makeThumb($src,$newWidth) {

$srcImage = imagecreatefromjpeg($src);
$width = imagesx($srcImage);
$height = imagesy($srcImage);

$newHeight = floor($height*($newWidth/$width));

$newImage = imagecreatetruecolor($newWidth,$newHeight);

imagecopyresized($newImage,$srcImage,0,0,0,0,$newWidth,$newHeight,$width,$height);

imagejpeg($newImage);
}
?>
<img src=”thumbnail.php?image=thumbnail.jpg&width=100”>


In the example above we are asking to resize the thumbnail.jpg to 100px wide
Change thumbnail.jpg to your own image and also change the width to anything you like.

The great thing about this script, is that as long as you specify your width, it will resize the height automatically, and will not stretch your image.

You can make life easier by just including the script in an include for your page which means you only need to call it once. Please take a look at the example below.

<?php include "thumbnail.php"; ?>
<img src=”thumbnail.php?image=thumbnail.jpg&width=100”>
Related Links:
- http://www.devirtuoso.com/2009/07/easy-thumbnails-with-php/