Upload image and resize it in php

Hello friends. Here is a simple php function to resize an image with new height and width . You just need to pass the currently uploaded file and new dimensions to which the image to be manipulated. The full php code is given here.

The php code
 
    
  //Function to save image with different height and width
  
  function saveImage($fileName,$newWidth,$newHeight){
  
  $ext=end(explode('.',$fileName));  
  
      if($ext=="jpg" || $ext=="jpeg" )
          $srcImage = imagecreatefromjpeg($fileName);
      else if($ext=="png")
          $srcImage = imagecreatefrompng($fileName);
      else
          $srcImage = imagecreatefromgif($fileName);
  
  list($width,$height)=getimagesize($fileName);
  
  $tmpImage=imagecreatetruecolor($newWidth,$newHeight);
  imagecopyresampled($tmpImage,$srcImage,0,0,0,0,
  $newWidth,$newHeight,$width,$height);
  
  $save="images/".$newWidth.'X'.$newHeight.'X'.time().'.'.$ext;
  
  imagejpeg($tmpImage,$save,100);
  
  imagedestroy($srcImage);
  imagedestroy($tmpImage);
  
  return $save;
  }
  
  // Do this when the form is submitted
  
  if(isset($_REQUEST['submit'])){
  
  if(is_uploaded_file($_FILES["file"]["tmp_name"])){
      $fileName =time().$_FILES["file"]["name"];
      $ext=end(explode('.',$fileName));   
         
    if($ext != 'jpg' && $ext != 'jpeg' && 
    $ext != 'gif' && $ext != 'png'){
       echo 'Invalid File !!';
    }else{
   move_uploaded_file($_FILES['file']['tmp_name'],$fileName);
   $bigImage=saveImage($fileName,300,150);
   echo $bigImage.'<br />';
   $mediumImage=saveImage($fileName,200,100);
   echo $mediumImage.'<br />';
   $smallImage=saveImage($fileName,100,50);
   echo $smallImage.'<br />';
   unlink($fileName);
    }
    }
  else {
  echo 'Select File !!';
  }
  }


The Html Form

 <form action="" enctype="multipart/form-data" 
 method="post" name="uploadForm">
  Upload File :
  <input name="file" size="30" type="file" />
  <input name="submit" type="submit" value="Upload" />
 </form>

Upload image and resize it in php Upload image and resize it in php Reviewed by Altaf Hussain on 3:06 PM Rating: 5

3 comments:

  1. Hi Altaf , i want to show 1st 15 members of my (MLM project) binary tree using php.if you have a binary tree scrpit please help me.I have urgency...

    ReplyDelete
  2. hi mate! I need to resize & save the image from the url..can u give any suggestion on this??

    ReplyDelete
    Replies
    1. If you want to download and save images from a url use this link
      http://altafphp.blogspot.in/2013/02/download-files-using-curl.html
      And after downloading it use above function to resize it.

      Delete

Altaf Web. Powered by Blogger.