Generating Thumbnails

Hello again.

I know I’ve posted on this topic before, but I figured instead of bumping the same question from a month ago, I’d go ahead and create a new topic instead.

I am making an attempt to write my own thumbnail generation script that will basically generate thumbnails from images in one directory and move them to a thumbnail directory. I specifically want to re-size the thumbnails; no cropping, so as to maintain aspect ratio and yet keep the thumbnail as close to the original in terms of content.

I’ll be honest when I say that I am probably overextending myself here considering I have had virtually no experience in PHP, let alone any true programming language, so my grasps at thinking in terms of computer logic are at best minimal.

So my question lies in how I can correctly implement such a script, and for others to check, and comment on improvements that could be made. Here is what I have so far:

( gen_thumbs.php )
[php]

<?php //This Script Will Generate Thumbnails From Uploaded Files (Or Existing Files in the img Directory) //It Will Also Attempt to Extract MetaInformation and Insert It Into A Database #DEFINE THE FILE URLS #Directories $img_dir = 'C:\WEB\Apache2.4\htdocs\DD\media\img\\'; $thumb_dir = 'C:\WEB\Apache2.4\htodcs\DD\media\thumbs_img\\'; #File Info $file = 'acwork.jpg'; $path = $img_dir . $file; # INCLUDE image utilities include_once $_SERVER['DOCUMENT_ROOT'] . '\img_utils.php'; # = = = = = = = = = = = = = = = = = = = = # # THUMBNAIL GENERATION SCRIPT STARTS HERE # # = = = = = = = = = = = = = = = = = = = = # // Check read permissions for the image directory, and insert them into an array analyze_directory($img_dir); // Create a loop that iterates through each file entry. Checks for file type (mime), analyzes for file tampering (security), and retrieves the properties of the image for calculating thumbnail dimensions and creation. # Currently only prints a list of the files. $counter = 0; $stop_count = $file_count - 1; while ($counter <= $stop_count) { echo 'File No. '. $counter . ': ' . $file_list[$counter] . '
'; $counter++; } /* #LOAD IMAGE function LoadJPEG($path, $file) { $jpg_rsc = imagecreatefromjpeg($path); #Check to see if image exists if($jpg_rsc) { } else { #Create A Black Image $jpg_rsc = imagecreatetruecolor(133, 100); $bgc = imagecolorallocate($jpg_rsc, 255, 255, 255); $tc = imagecolorallocate($jpg_rsc, 0, 0, 0); imagefilledrectangle($jpg_rsc, 0, 0, 133, 100, $bgc); #Show Error Message imagestring($jpg_rsc, 1, 6, 6, $file, $tc); } return $jpg_rsc; } #START IMAGE CHECK #Check to see if the file exists if(file_exists($path)) { #File Exists, Check to see if the file is a JPEG file if(exif_imagetype($path) == 2) { echo 'File type is valid JPEG file. Continuing Processing.
'; $_IMAGE = exif_read_data($path); #Change File Size Into Human Readble Form //Check if a number is present if(isset($_IMAGE['FileSize']) && !empty($_IMAGE['FileSize'])) { echo 'File size verified, commencing thumbnail generation.
'; #Reassign Variable from Array $file_size = $_IMAGE['FileSize']; #Call Formatting Function, assign to form size $form_size = format_fsize($file_size, 2); } else { echo 'NOTICE: File size missing! Omitting original file size; commencing thumbnail generation.
'; } #Obtain Dimensions of Target Image $_DIMS = getimagesize($path); if(isset($_DIMS) && !empty($_DIMS)) { #Assign Dimensions to Appropriate Variables $h_orig = $_DIMS['1']; $w_orig = $_DIMS['0']; $constant_dim = 100; echo 'Image Dimensions: ' . $w_orig . ', ' . $h_orig . '
'; #Determine Which Dimension is larger if($h_orig > $w_orig) { new_dim_height($h_orig, $w_orig, $constant_dim); } elseif($h_orig < $w_orig) { new_dim_width($w_orig, $h_orig, $constant_dim); } else { new_dim_ratio($w_orig, $constant_dim); } } else { die('Dimensions are missing from image! Thumbnail generation cannot continue! Back'); } #Prepare the Retrieved Date for database Insertion (sanitize first) $datetime = $_IMAGE['DateTimeOriginal']; prep_date($datetime); #Load the Image $img = LoadJPEG($path, $file); #Set New Image File Name $thumb = 'test_' . $file; #Display Image imagejpeg($img, $thumb); imagedestroy($img); #Setup Paths to move generated image $tmp_path = $tmp_dir . $thumb; $new_path = $thumb_dir . $thumb; $tmp_dir = 'C:\HADELWEB\Apache2.4\htdocs\DD\\'; echo $tmp_dir . $thumb . '
'; echo $new_path . '
'; #Move Image to New Directory echo getcwd() . '
'; #Check to see if File Already Exists if(file_exists($new_path)) { echo 'File already exists! New thumbnail will not be placed in thumbnail directory.'; } #Otherwise, Copy the file over to the directory else { copy($tmp_path, $new_path); #Check for Sucess or Failure if(file_exists($new_path)) { echo 'File Move Sucessful!
'; } else { echo 'File Move Failure!
'; } } #Print The Final Image Properties [ DEBUG ] echo '

Image Properties

'; echo '

Filename: ' . $_IMAGE['FileName'] . '

'; echo '

' . $form_size . '

'; echo '

' . $_IMAGE['DateTimeOriginal'] . '

'; echo '

Height [Pels]: ' . $h_orig . '

'; echo '

Width [Pels]: ' . $w_orig . '

'; echo '

Image

'; echo 'Image Unavailable'; } else { die('File type is unacceptable.'); } } else { die('The file ' . $file . ' does NOT exist!'); } //TO DO #Loop Through All Files Until File Match Is Found #Find Files that Match .png or .jpg or .jpeg #Check For File Metadata #Obtain Date Photo Taken, Any Caption Information, File Name, and also note the current time at which script was processed. #Generate the Thumbnail #Save the Thumbnail in the temporary directory #Transfer the newly generated thumnbnail to the img directory #Write Metadata back to original image as well as the thumbnail to preserve original timestamps. #Start the process again. * */ ?>

[/php]

( img_utils.php )

[php]

<?php #Check the supplied path for a directory, permissions to read, and if there are files inside. function analyze_directory($dir) { if (is_dir($dir)) { if (is_readable($dir)) { echo '

Accessing image directories.

'; $handle = opendir($dir); if ($handle) { $key = 0; global $file_list; $file_list = array($file); while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $file_list[$key] = $entry; $key++; } } global $file_count; $file_count = $key; } else { echo '

ERROR: Cannot create handle for directory.

'; } closedir($handle); } else { echo '

ERROR: Directory is unable to be accessed. Administrators are advised to check permissions settings for the web server.

'; } } else { echo '

ERROR: It seems that a directory was not supplied properly.

'; } } #Human Format File Size function format_fsize($file_size, $precision) { #Format the File Size so it is always between 1 and 999.49 $base = log($file_size) / log(1024); #Create The Human Readble Unit Array $unit_suffix = array('BY', 'KB', 'MB'); #Assemble the Formatted File Size return round(pow(1024, $base - floor($base)), $precision) . ' ' . $unit_suffix[floor($base)]; } #The Image is Slender ( Tall ) function new_dim_height($h_orig, $w_orig, $constant_dim) { $h_raw = ($h_orig * $constant_dim)/$w_orig; $h_thumb = floor($h_raw); echo 'New Height: ' . $h_thumb . '
'; return $h_thumb; } #The Image is Bulky ( Wide ) function new_dim_width($w_orig, $h_orig, $constant_dim) { $w_raw = ($w_orig * $constant_dim)/$h_orig; $w_thumb = floor($w_raw); echo 'New Width: ' . $w_thumb . '
'; return $w_thumb; } #The Image is Square function new_dim_ratio($w_orig, $constant_dim) { $scaling_ratio = $w_orig / $constant_dim; echo 'Sizing Ratio: ' . $scaling_ratio . '
'; return $scaling_ratio; } // DATE REFORMATTING FUNCTION function prep_date($datetime) { list($date, $time) = explode(" ", $datetime); echo $date . ',' . $time . '
'; #Slashes Tell Where $SQL_date = preg_replace('/:/', '-', $date); echo $SQL_date . '
'; return $SQL_date; } ?>

[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service