Snipe.Net Geeky, sweary things.

Dynamic thumbnailing with PHP and the GD library

D

Although there are loads of ways you can do this, for this example, we’re assuming that the fullsize image is located in a directory called “images”, and the thumbnails will have the same name as the fullsize, but will be copied into a directory called “thumbs”.

<?php
// find out the current size info
$photo_filename = "myimage.jpg"
$path = "/home/snipe/www/images/";
$image_stats = GetImageSize($path.$photo_filename);
$imagewidth = $image_stats[0];
$imageheight = $image_stats[1];
$img_type = $image_stats[2];
$new_w = 100; $ratio = ($imagewidth / $new_w);
$new_h = round($imageheight / $ratio);

// Find out if we need to resize it by checking to
// see if the original image is larger than the
// defined new width, and making sure the
// resized version does not exist yet

if (($imagewidth > $new_w)&& (!file_exists($path.$photo_filename))) {

// if this is a jpeg, resize as a jpeg
if ($img_type==2) {

$src_img = imagecreatefromjpeg($path.$photo_filename);
$dst_img = imagecreate($new_w,$new_h);
imagecopyresized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
imagejpeg($dst_img, $path.$photo_filename);

} elseif ($img_type==3) {
// if image is a png, copy it

$dst_img=ImageCreate($new_w,$new_h);
$src_img=ImageCreateFrompng($path.$photo_filename);
ImageCopyResized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,ImageSX($src_img),ImageSY($src_img));
Imagepng($dst_img, $path.$photo_filename);

// Normally if image is neither png nor jpeg
// (ie, invalid image or a gif file), I use
// the fullsize as the thumbnail and just
// resize it through the html size tags. For this
// example tho, we’ll pretend we have a version of
// Gdlib that can handle gif resizing

} elseif ($img_type==1) {

$dst_img=ImageCreate($new_w,$new_h);
$src_img=ImageCreateFromGif($path.$photo_filename);
ImageCopyResized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,ImageSX($src_img),ImageSY($src_img));
ImageGif($dst_img, $path.$photo_filename);

} else {
// if it doesn’t show up as any of the valid formats, give an error
echo ‘error’;

} // endif img_type sequence

}

?>

About the author

snipe

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

By snipe
Snipe.Net Geeky, sweary things.

About Me

I'm a tech nerd from NY/CA now living in Lisbon, Portugal. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead, skeet me at @snipe.lol, or read more...

Get in Touch