Return to Snippet

Revision: 17578
at September 9, 2009 21:20 by brandonio21


Initial Code
<?php
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
  // open the directory

  $dir = opendir( $pathToImages );

  // loop through it, looking for any/all JPEG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpeg' )
    {
      //echo "Creating thumbnail for {$fname} <br />";

      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
      $new_width = $thumbWidth;
	 $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
//Data Text Save [OPTIONAL]
    //$myFile = "data.txt";
    //$fh = fopen($myFile, 'a') or die("can't open file");
    //$stringData = $fname."\n";
    //fwrite($fh, $stringData);

    //fclose($fh);
    }
  }
  
  // close the directory
  closedir( $dir );
}
?>

Initial URL


Initial Description
This code is not made by me : But it was used for one of my projects.
This code scans for all jpeg 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.:

Initial Title
PHP Create Thumbnails [JPEG]

Initial Tags
php

Initial Language
PHP