Page 1 of 1

Upload module auto generate thumbnail from the original image uploaded

Posted: Tue Mar 18, 2008 8:28 am
by geniemorty
How do I let the Upload Module auto generate thumbnail and save it as "thumb_" to the same image folder? Due to some special circumstance I don't want to use thumbnail options available in the Upload module.

I believe the code is somewhere in the Uploads.module.php file. And I found out some webpage which got the script to auto generate thumbnail at the same time user upload the images. Here is the link:

http://www.reconn.us/image_thumbnail.html

I try to embed the script above into the _handleUpload function in uploads.module.php & the coding as below:

Code: Select all

function _handleUpload ($destDir, $realAuthor, $maxFileSize = false, $fieldName = '_upload', $nameCallback = false,
													$destname = '',$enforceextension = true,
													$replace_existing = false)
  {


    //make sure something is there
    if (!isset ($_FILES[$fieldName]) || !isset ($_FILES)
				|| !is_array ($_FILES[$fieldName]) || !$_FILES[$fieldName]['name'])
      {
				return array (false, $this->Lang('error_nofilesuploaded'));
      }

    //normalize the file variable
    $theAuthor = $realAuthor;
    $file = $_FILES[$fieldName];
    if (!isset ($file['type']))
      $file['type'] = '';
    if (!isset ($file['size']))
      $file['size'] = '';
    if (!isset ($file['tmp_name']))
      $file['tmp_name'] = '';
    $file['name'] =
      preg_replace('/[^a-zA-Z0-9\.\$\%\'\`\-\@\{\}\~\!\#\(\)\&\_\^]/', '',
									 str_replace (array (' ', '%20'), array ('_', '_'), $file['name']));

    // validate the filename
    if (!$this->_isValidFilename ($file['name']))
      {
				return array (false, $this->Lang ('error_invaliduploadfilename',$file['name']));
      }

    //was it to big?
    if ($maxFileSize && ($file['size'] > ($maxFileSize * 1024)))
      return array (false, $this->Lang ('error_filetoolarge'));

    //normalize destDir
    if (strlen ($destDir) > 0 && $destDir[strlen ($destDir) - 1] != "/")
      $destDir = $destDir.'/';

    // get the destination name
    if( $destname == '' ) {
      $destname = $file['name'];
    }
    
    //should we change the filename via a callback?
    if ($nameCallback)
      {
				$destname =
					call_user_func_array ($nameCallback, array ($file, $destDir));
      }

    if( $enforceextension == true && $this->GetPreference('requirefilename_extensions',1))
      {
				// make sure it has an extension
				// if it doesn't have one, we give it one (the one off the input file)
				if( strpos($destname,'.') == false )
					{
						if( ($p = strpos( $file['name'], '.' ) ) != false )
							{
								$destname = $destname . substr( $file['name'], $p );
							}
					}
      }

    // and clean it up
    $destname = 
      preg_replace('/[^a-zA-Z0-9\.\$\%\'\`\-\@\{\}\~\!\#\(\)\&\_\^]/', '',
									 str_replace (array (' ', '%20'), array ('_', '_'), $destname));

    if( $replace_existing == false )
      {
				if( file_exists( $destDir.$destname ) && $replace_existing == false ) {
					return array( false, $this->Lang( 'error_fileexists', $destDir.$destname ));
				}
      }

    //and now the big moment





 //HERE ARE THE THUMBNAIL CODES FROM THE LINK I PROVIDED ABOVE

$newName2 = $file['name'];

    if (!@copy ($file['tmp_name'], $destDir.$destname))
      {
				return array (false,
											$this->Lang ('error_couldnotwrite').
											':&nbsp'.$file['name']." -> ".$destDir." ".
											$this->Lang ('error_permissiondenied'));
      }
    else
      {

				// define the width and height for the thumbnail
				define ("WIDTH","150"); 
				define ("HEIGHT","100");

                                // the new thumbnail image will be placed in same image folder
				$thumb_name= $destDir.'thumb_'.$file['name'];

				$thumb = $this->make_thumb($newName2,$thumb_name,WIDTH,HEIGHT);

				if(!$thumb)
				{
					return array (false, "Failed to generate thumbnail  for the image ". $newName2);
				}
				else
				{
					return array (true, array('name' => $destname, 'size' => $file['size'], 'dir' => $destDir ));
	                         }
                 }
  }
After that at the last section I place the make_thumb function:

Code: Select all

function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);

//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken: 
// 1. calculate the ratio by dividing the old dimmensions with the new ones
//	 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
//	 and the height will be calculated so the image ratio will not change
//	 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2)	{
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else	{
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 

// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename); 
else
imagejpeg($dst_img,$filename); 

//destroys source and destination images. 
imagedestroy($dst_img); 
imagedestroy($src_img); 
}
Following by this little function code to check the extension:

Code: Select all

// This function reads the extension of the file. 
// It is used to determine if the file is an image by checking the extension. 
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
It cannot output the thumbnail and i believe its something wrong within the path  ??? I not a good coder & I hope anyone of you can guide me through this. Your help is greatly appreciated.


Eric