Create Thumbnail on The Fly Using PHP and GD

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.
< ?php 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.
< ?php // 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:
< ?php //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 &lt;IMG SRC=”thumbnail.php?image=img/picture.jpg&width=150″ /&gt;

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

&nbsp;

2 thoughts on “Create Thumbnail on The Fly Using PHP and GD

  1. 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. Kalo webnya rame bisa peyok servernya, mbak, servere perlu jamu sing akeh ^_^

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

Leave a Reply