Create Thumbnail on The Fly Using PHP and GD

December 2, 2006 | PHP

Here’s a cool script I use to resize picture on the fly. I don’t wanna loose any space in my server, so instead of creating a real thumbnail file, I generate a thumbnail on the fly.

First, specify the HTTP header.
header("Content-type: image/jpeg");

Then, this is the formula to resize the image with aspect ratio. We will only need to specify new thumbnail's width. And its height will be automatically set.
// get image size
$file = $_GET[image];
if($size = GetImageSize($file)){
$w = $size[0];
$h = $size[1];

//set new size
$nw = $_GET['width'];
$nh = ($nw*$h)/$w;
}
else{
//set new size
$nw = "0";
$nh = "0";
}
?>

Now let's draw the image:
//draw image
$src_img = imagecreatefromjpeg($file);
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $w, $h);
imagejpeg($dst_img,"",100);
imagedestroy($src_img);
imagedestroy($dst_img);
?>

Save above pieces code into a file, name it thumbnail.php, for example. Then, call it with common <IMG SRC="thumbnail.php?image=img/picture.jpg&width=150" />

Your image should be succesfully displayed. If you have any question, please don't hesitate to contact me yeni.setiawan AT yahoo DOT com ^_*

 

2 comments

This post has 2 comments, woohoo!

  1. Arief Fajar Nursyamsu 18/12/2006 at 03:51

    Thanks for this simple tutorial.

    What do you think about the server load if you create all images on the fly, especially when you have a photo gallery?

    It’s not a good option to use PHP to create image on the fly for gallery. Best method, I think, is generating thumbnail when upload the image.

  2. Aryo Sanjaya 22/12/2006 at 02:41

    Kalo webnya rame bisa peyok servernya, mbak, servere perlu jamu sing akeh ^_^

    Bener sampeyan, ini cuma kondisional dan jika bener2 kepepet ^o^

 

Leave a comment

Allowed tags are: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>