PHP Create Thumbnails [PNG]


/ Published in: PHP
Save to your folder(s)

This code is not made by me : But it was used for one of my projects. This code scans for all png files in a directory and creates a 100x100 thumbnail and moves it into a specified directory.

:.INCLUDES A DATA TEXT CODE WHICH PUTS THE NAMES OF ALL FILES IN THAT DIRECTORY INTO A TEXT FILE, WHICH IS SAVED AS data.txt.:


Copy this code and paste it in your HTML
  1. <?php
  2. function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
  3. {
  4. // open the directory
  5.  
  6. $dir = opendir( $pathToImages );
  7.  
  8. // loop through it, looking for any/all PNG files:
  9. while (false !== ($fname = readdir( $dir ))) {
  10. // parse path for the extension
  11. $info = pathinfo($pathToImages . $fname);
  12. // continue only if this is a PNG image
  13. if ( strtolower($info['extension']) == 'png' )
  14. {
  15. //echo "Creating thumbnail for {$fname} <br />";
  16.  
  17. // load image and get image size
  18. $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
  19. $width = imagesx( $img );
  20. $height = imagesy( $img );
  21.  
  22. // calculate thumbnail size
  23. $new_width = $thumbWidth;
  24. $new_height = floor( $height * ( $thumbWidth / $width ) );
  25.  
  26. // create a new temporary image
  27. $tmp_img = imagecreatetruecolor( $new_width, $new_height );
  28.  
  29. // copy and resize old image into new image
  30. imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
  31.  
  32. // save thumbnail into a file
  33. imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
  34. //Data Text Save [OPTIONAL]
  35. //$myFile = "data.txt";
  36. //$fh = fopen($myFile, 'a') or die("can't open file");
  37. //$stringData = $fname."\n";
  38. //fwrite($fh, $stringData);
  39.  
  40. //fclose($fh);
  41. }
  42. }
  43.  
  44. // close the directory
  45. closedir( $dir );
  46. }
  47. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.