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 <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 ^_*
Arief Fajar Nursyamsu
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?
Aryo Sanjaya
Kalo webnya rame bisa peyok servernya, mbak, servere perlu jamu sing akeh ^_^