Upload and Resize Image in PHP

we often need to implement logic for uploading and resizing images in php. if we are building application in core php then we have write code for upload and resize image.Below is the core php code for upload and resize image.

We will create two files one for upload form and another one to handle upload and resize.

1. index.php

2. upload_file.php

It is very simple straightforward task. In order to complete this task first of all we will create a file upload form.
Below is the code of file upload form.

    1.  <form action="upload_file.php" method="post" enctype="multipart/form-data">
    2.  <label for="file">Filename:</label>
    3.  <input type="file" name="file" id="file"><br>
    4.  <input type="submit" name="submit" value="Submit">
    5.  </form>

In above code we have created a form and a file field. We have added an extra attribute in form enctype=”multipart/form-data” this is required to upload file with POST data else file upload will not work

When user submit the form it will post the file data to upload_file.php file. below is the code of upload_file.php

    1.  if($_FILES) {
  
    2.      $allowedExts = array("gif", "jpeg", "jpg", "png");
      
    3.      $temp = explode(".", $_FILES["file"]["name"]);
      
    4.      $extension = end($temp);
      
    5.      if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png")  || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {
    
    6.          if ($_FILES["file"]["error"] > 0) {
          
    7.              echo "Return Code: " . $_FILES["file"]["error"] . "\n";
          
    8.          } else {
          
    9.              echo "Upload: " . $_FILES["file"]["name"] . "\n";
    
    10.             echo "Type: " . $_FILES["file"]["type"] . "\n";
    
    11.             echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB\n";
    
    12.             echo "Temp file: " . $_FILES["file"]["tmp_name"] . "\n";
          
    13.             $filename = "upload/" . $_FILES["file"]["name"];
          
    14.             move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
          
    15.             $resized_filename = "upload/" . 'thumb-'.$_FILES["file"]["name"];
          
    16.             resize_image($filename, $resized_filename, 50, 50);
    
    17.             echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
          
    18.         }
    
    19.     } else {
    
    20.         echo "Invalid file";
    
    21.     }
    
    22. }
    
  

In above code at line 5 we are checking the valid extensions of uploaded image to avoid unnecessary errors.

At the line 13 we are building the destination path where image will be get saved and we are using the same name as the name of uploaded image.

At the line 14 the function move_uploaded_file is doing the actual work of uploading image to target location.

Now we need to resize the image to a particular dimension to create thumbnail so at the line 15 we are generating new name for thumbnail image to avoid overwriting images. then we have passed the path of uploaded image, Path of thumb image, width and height to the resize_image function. this function will resize this image to given dimension and stores with given name at same location.

    1.  function resize_image($file, $destination, $w, $h) {
    
    2.      //Get the original image dimensions + type
    
    3.      list($source_width, $source_height, $source_type) = getimagesize($file);
    
    4.      //Figure out if we need to create a new JPG, PNG or GIF
    
    5.      $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    
    6.      if ($ext == "jpg" || $ext == "jpeg") {
    
    7.          $source_gdim=imagecreatefromjpeg($file);
    
    8.      } elseif ($ext == "png") {
    
    9.          $source_gdim=imagecreatefrompng($file);
    
    10.     } elseif ($ext == "gif") {
    
    11.         $source_gdim=imagecreatefromgif($file);
    
    12.     } else {
    
    13.         //Invalid file type? Return.
    
    14.         return;
    
    15.     }

    16.     //If a width is supplied, but height is false, then we need to resize by width instead of cropping
    
    17.     if ($w && !$h) {
    
    18.         $ratio = $w / $source_width;
    
    19.         $temp_width = $w;
    
    20.         $temp_height = $source_height * $ratio;

    21.         $desired_gdim = imagecreatetruecolor($temp_width, $temp_height);
    
    22.         imagecopyresampled($desired_gdim,$source_gdim,0, 0,0, 0,$temp_width, $temp_height,$source_width, $source_height);
    
    23.     } else {
    
    24.         $source_aspect_ratio = $source_width / $source_height;
    
    25.         $desired_aspect_ratio = $w / $h;

    26.        if ($source_aspect_ratio > $desired_aspect_ratio) {
    
    27.             $temp_height = $h;
    
    28.              $temp_width = ( int ) ($h * $source_aspect_ratio);
    
    29.         } else {
    
    30.             $temp_width = $w;
    
    31.             $temp_height = ( int ) ($w / $source_aspect_ratio);
    
    32.         }
    
    33.         $temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
    
    34.         imagecopyresampled($temp_gdim,$source_gdim,0, 0,0, 0,$temp_width, $temp_height,$source_width, $source_height);
    
    35.         $x0 = ($temp_width - $w) / 2;
    
    36.         $y0 = ($temp_height - $h) / 2;
    
    37.         $desired_gdim = imagecreatetruecolor($w, $h);
    
    38.         imagecopy($desired_gdim,$temp_gdim,0, 0,$x0, $y0,$w, $h);
    
    39.     }
    
    41.     if ($ext == "jpg" || $ext == "jpeg") {
    
    42.         ImageJpeg($desired_gdim,$destination,100);
    
    43.     } elseif ($ext == "png") {
    
    44.         ImagePng($desired_gdim,$destination);
    
    45.     } elseif ($ext == "gif") {
    
    46.         ImageGif($desired_gdim,$destination);
    
    47.     } else {
    
    48.         return;
    
    49.     }
    
    50.     ImageDestroy ($desired_gdim);
    
    51. }
    

Please download the working code from download link.

Leave a Reply

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

13 + seventeen =