Wednesday 23 March 2016

Upload Resize Image using Ajax Jquery PHP without Page Refresh



In this post we are going to learn Ajax upload and resize an Image using PHP and Jquery. In this I have used Jquery FormData() Object with Ajax for upload image without page refresh. When User upload image to server then at that time page will not be refresh and after completing image upload it will display image on the web page without page refresh. In Now a days most of the social media sites like facebook, twitter using this functionality like upload image without page refresh. I have make some validation for uploading image. Validation like image is selected or not, allowed image file formate, size of image. If this validation pass image file then after it will upload to server without page refresh. I have used some php image function like getimagesize() function for getting width and height of uploaded image, imagecreatefrompng() function for create new image if png image, imagecreatefromjpeg() function for create new image from if image file is jpg or jpeg. For resize I have define new width and to maintain aspect ratio I have divide height by width into new height. I have also used other php image function like imagecreatetruecolor() function for create blank image, imagecopyresampled() function is copy portion of source image to destination image, imagejpeg() function is used for create image new image and last is imagedestroy image is used for destroy image from memory.



Source Code


index.php



<html>  
 <head>  
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
  <meta charset="utf-8">  
  <title>Webslesson Tutorial</title>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
 </head>  
 <body>  
  <div class="container">  
   <br />  
   <br />  
   <h3>Upload & Resize Image using Ajax Jquery PHP without Page Refresh</h3><br />  
   <form method="post" id="upload_image" enctype="multipart/form-data">
    <label>Select File <br />  
    <input type="file" name="image_upload" id="image_upload" />
    <br />
    <input type="submit" name="upload" id="upload" class="btn btn-info" value="Upload" />
   </form>
   <br />  
   <br />  
   <div id="preview"></div>  
   <br />  
   <br />  
  </div>  
 </body>  
</html>  
<script>  
$(document).ready(function(){   
    $('#upload_image').on('submit', function(event){
     event.preventDefault();
     $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      contentType:false,
      cache:false,
      processData:false,
      success:function(data){
       $('#preview').html(data);
      }
     })
    });
});  
</script>


upload.php



<?php  
//upload.php;
if(isset($_FILES["image_upload"]["name"])) 
{
 $name = $_FILES["image_upload"]["name"];
 $size = $_FILES["image_upload"]["size"];
 $ext = end(explode(".", $name));
 $allowed_ext = array("png", "jpg", "jpeg");
 if(in_array($ext, $allowed_ext))
 {
  if($size < (1024*1024))
  {
   $new_image = '';
   $new_name = md5(rand()) . '.' . $ext;
   $path = 'upload/' . $new_name;
   list($width, $height) = getimagesize($_FILES["image_upload"]["tmp_name"]);
   if($ext == 'png')
   {
    $new_image = imagecreatefrompng($_FILES["image_upload"]["tmp_name"]);
   }
   if($ext == 'jpg' || $ext == 'jpeg')  
            {  
               $new_image = imagecreatefromjpeg($_FILES["image_upload"]["tmp_name"]);  
            }
            $new_width=200;
            $new_height = ($height/$width)*200;
            $tmp_image = imagecreatetruecolor($new_width, $new_height);
            imagecopyresampled($tmp_image, $new_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($tmp_image, $path, 100);
            imagedestroy($new_image);
            imagedestroy($tmp_image);
            echo '<img src="'.$path.'" />';
  }
  else
  {
   echo 'Image File size must be less than 1 MB';
  }
 }
 else
 {
  echo 'Invalid Image File';
 }
}
else
{
 echo 'Please Select Image File';
}
?>

9 comments:

  1. Nice work!

    How ever using the script generate this error: Only variables should be passed by reference in C:\xampp\htdocs\files\uploads.php on line 7

    Line 7 and 8 belowe:

    $ext = end(explode(".", $name));
    $allowed_ext = array("png", "jpg", "jpeg");

    ReplyDelete
    Replies
    1. $ext = explode(".", $name);
      $ext = end($ext);
      $ext = strtolower($ext);

      Delete
    2. $ext = end(explode(".", $name)); changed into
      $ext0 = explode(".", $name);
      $ext= $ext0[1];

      Delete
  2. Cannot upload and always loading.
    what you use jquery.js library version..??

    ReplyDelete
  3. Cant upload image to Upload Directory... Bug in the code, Whatz the use of jquery.form.js??

    ReplyDelete
  4. Select File
    Choose File

    Upload


    --Notice: Only variables should be passed by reference in
    C:\xampp\htdocs\test\uploadandresize\upload.php on line 7

    --Warning: imagejpeg(upload/6f69541498fa2744313b5328044981a3.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\test\uploadandresize\upload.php on line 29

    ReplyDelete