cropping and creating thumbnail image in php

When we upload image, it is better to crop the image so that the image easily fits in the space provided. In the following example, an image is cropped and its thumbnail is created. Cropped image is stored in its directory whereas thumbnail image is stored in its directory.

To test the example, you need to set the paths defined in constant definition function “define”

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/master.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Search lost and found items" />
<meta name="keywords" content="report lost item, report found item, lost and found pakistan, pakproject, search lost items" />
<title>lostandfound post</title>
</head>

<body>

<?php

define("ITEM_IMG_DIR","A:/AAA/www/web/uploads/");
define("THUMB_IMG_DIR","A:/AAA/www/web/uploads/thumbs/"); 
define("IMAGE_WIDTH",200); // set the width you want of image
define("THUMBNAIL_WIDTH",50); // set the width you want of thumbnail          

if( isset($_POST['btnSave'] ) )
{
    
  

foreach($_FILES['fileImage']['name'] as $key => $error )
{		
    if( $error == UPLOAD_ERR_OK)
    {		  
       $imgName = $_FILES['fileImage']['name'][$key];
       $tmpName = $_FILES['fileImage']['tmp_name'][$key];		   
          	   
      
      if( trim(strlen($imgName))!=0 && trim(strlen($tmpName))!=0 )
      {
        handleImage($imgName, $tmpName);
      }
    }		   
}		  	


  
  
  
}	

function handleImage($imgName, $tmpName)
{
  $newName="";
    $newthumbName="";

       // we need to rename the image name just to avoid
       // duplicate file names
       // first get the file extension
       $ext = strrchr($imgName, ".");
    
       // then create a new random name
       $namecode = md5(rand() * time()); 
       
       // name of image file
       $newName = $namecode . $ext;
       
       // name of thumbnail file
       $newthumbName = $namecode . "_thumb" . $ext;
    
       // the album image will be saved here
       $imgPath = ITEM_IMG_DIR . $newName;
       $bigimgPath = THUMB_IMG_DIR . $newthumbName;
       
      
    
       // resize all album image
      $result1 = createThumbnail($tmpName, $imgPath, IMAGE_WIDTH);
      $result2 = createThumbnail($tmpName, $bigimgPath, THUMBNAIL_WIDTH);
      
  global $imgsarray, $thumbsarray;

  
  if(strlen($result1)!=0 && strlen($result2)!=0)
  {
    // Image uploaded		
    
  }
  else
  {
    
  
  }
  
  
}



//
//	Create a thumbnail of $srcFile and save it to $destFile.
//	The thumbnail will be $width pixels.
//
function createThumbnail($srcFile, $destFile, $width, $quality = 75)
{
  $thumbnail = '';
  
  if (file_exists($srcFile)  && isset($destFile))
  {
    $size        = getimagesize($srcFile);
    $w           = number_format($width, 0, ',', '');
    if($size[0] <= 0)
    {			
      return "";
    }
    else
    {
    $h           = number_format(($size[1] / $size[0]) * $width, 0, ',', '');		
    $thumbnail =  copyImage($srcFile, $destFile, $w, $h, $quality);
    }		
  }
  
  // return the thumbnail file name on sucess or blank on fail
  return basename($thumbnail);
}



//
//	Copy an image to a destination file. The destination
//	image size will be $w X $h pixels
//
function copyImage($srcFile, $destFile, $w, $h, $quality = 75)
{
    $tmpSrc     = pathinfo(strtolower($srcFile));
    $tmpDest    = pathinfo(strtolower($destFile));
    $size       = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
       $destFile  = substr_replace($destFile, 'jpg', -3);
       $dest      = imagecreatetruecolor($w, $h);
       //imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
       $dest = imagecreatetruecolor($w, $h);
       //imageantialias($dest, TRUE);
    } else {
      return false;
    }

    switch($size[2])
    {
       case 1:       //GIF
           $src = imagecreatefromgif($srcFile);
           break;
       case 2:       //JPEG
           $src = imagecreatefromjpeg($srcFile);
           break;
       case 3:       //PNG
           $src = imagecreatefrompng($srcFile);
           break;
       default:
           return false;
           break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch($size[2])
    {
       case 1:
       case 2:
           imagejpeg($dest,$destFile, $quality);
           break;
       case 3:
           imagepng($dest,$destFile);
    }
    return $destFile;

}



?>

<form action="" method="post" enctype="multipart/form-data" name="form1">
   <table border="1">
   <tr>
          <td><input type="file" name="fileImage[]" id="fileImage[]" /></td>
  </tr>
  <tr>
          <td><input type="file" name="fileImage[]" id="fileImage[]" /></td>
  </tr>
  <tr>
          <td><input type="file" name="fileImage[]" id="fileImage[]" /></td>
  </tr>
  <tr>
          <td><input type="file" name="fileImage[]" id="fileImage[]" /></td>
  </tr>
     
   
   <tr>	
      
          <td><input type="submit" name="btnSave" id="btnSave" value="Save" onclick="return checkForm();" /></td>
         </tr>
     </table>  
      </form>
      
</body>
</html>

 

Add a Comment

Your email address will not be published. Required fields are marked *