Posted By

goo on 08/20/08


Tagged

php image thumbnail


Versions (?)

Who likes this?

19 people have marked this snippet as a favorite

jamesming
wizard04
lepetitcrack
JimiJay
latavish
fackz
Nix
PapTom
dsntos
Anber
vali29
adiian
Adam42
galofre
dinkan
bobbym245
dhavalpatel
wakeupandrage
hypertext03


PHP Create Thumbnail Images


 / Published in: PHP
 

URL: http://www.webcheatsheet.com/php/create_thumbnail_images.php

  1. <?php
  2. function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
  3. {
  4. // open the directory
  5. $dir = opendir( $pathToImages );
  6.  
  7. // loop through it, looking for any/all JPG files:
  8. while (false !== ($fname = readdir( $dir ))) {
  9. // parse path for the extension
  10. $info = pathinfo($pathToImages . $fname);
  11. // continue only if this is a JPEG image
  12. if ( strtolower($info['extension']) == 'jpg' )
  13. {
  14. echo "Creating thumbnail for {$fname} <br />";
  15.  
  16. // load image and get image size
  17. $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
  18. $width = imagesx( $img );
  19. $height = imagesy( $img );
  20.  
  21. // calculate thumbnail size
  22. $new_width = $thumbWidth;
  23. $new_height = floor( $height * ( $thumbWidth / $width ) );
  24.  
  25. // create a new temporary image
  26. $tmp_img = imagecreatetruecolor( $new_width, $new_height );
  27.  
  28. // copy and resize old image into new image
  29. imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
  30.  
  31. // save thumbnail into a file
  32. imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
  33. }
  34. }
  35. // close the directory
  36. closedir( $dir );
  37. }
  38. // call createThumb function and pass to it as parameters the path
  39. // to the directory that contains images, the path to the directory
  40. // in which thumbnails will be placed and the thumbnail's width.
  41. // We are assuming that the path will be a relative path working
  42. // both in the filesystem, and through the web for links
  43. createThumbs("upload/","upload/thumbs/",100);
  44. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: oggame on April 6, 2009

check this one out http://freelogic.pl/thumbnailer/

You need to login to post a comment.