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

}

?>

Advertisement

Themeforest

Advertisement

468x60_makemoney
Previous post

Dynamic thumbnailing with PHP and Imagemagick

Next post

Dynamic Watermarks/Text Overlay on Images in PHP

snipe

snipe

I’m a tech geek/dev/infosec-nerd/scuba diver/blacksmith/sword-fighter/crime fighter/ENTP/warcrafter/activist. I'm the CTO at Mass Mosaic and the CEO of Grokability, Inc. in San Diego, CA. Tweet at me @snipeyhead or read more...