Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

Sunday, 12 January 2020

Laravel 6 - Crop & Upload Image using jQuery with Ajax



Are you a learner of Laravel framework for web application development, So here in this post, you can find interesting topic like How to Crop an Image before uploading in Laravel framework. Here we have use Laravel 6 framework for make this type of feature in any web based application. If you want to learn How to Crop and Upload image in Laravel 6 framework by using jQuery with Ajax, so this post will help you to learn this topic.

Here we have use jQuery Croppie plugin used for Crop an Image before upload it. There are many jQuery plugin are available on internet for Crop image, but here we have use Croppie plugin with Laravel 6 framework for Crop image. Because it is widely used for Crop image, and it is easy to learn How to crop image. So, If you want to add feature like image crop for your web application, so you can use this plugin, because it is very easy to integrate in our web application.

In short, In this post we have use jQuery plugin for Crop an Image and by using Ajax we have upload on web server with Laravel 6 framework. Now in your mind how this Croppie plugin has work. So when page has been load into web browser, then this Croppie plugin has been initialize and once we have select image from our local computer then that selected image preview, we can see on web page. In that preview we can also zoom image, and we can drag the view port of the crop area also. So, this tutorial, you can find step by step process for How to Crop image by using Croppie plugin, and then after how to use Ajax for upload cropped image with Laravel 6 framework.

  • Download and Install Laravel 6 Framework
  • Create Controller Class
  • Create View Blade File
  • Set Route
  • Run Laravel 6 Application


Download and Install Laravel 6 Framework


If you want to use Laravel framework for you any web development task, so first you have to download and installed it in you local computer. For download Laravel 6 framework you have to go command prompt and go to directory in which you want to download Laravel framework, and after this you have to run following command in command prompt.


composer create-project --prefer-dist laravel/laravel laravel6


This command will make laravel6 folder and under this it will download Laravel 6 framework.




Create Controller Class


After download Laravel framework, so you are ready to use Laravel for web development. Here first we want to make Controller class for handle browser http request.So, for create Controller class we have to go command prompt and run following command

//Code
This command will make ImageCropController.php file in app/Http/Controllers folder. In this class we have make following method.

index() - This is the root method of this ImageCropController.php controller class. This method has load view file in browser.

upload() - This method has recieved Ajax request for upload Crop image. This method has received in image in binary string. By using base64_decode() method it will convert binary string to image format and by using file_put_contents() function image will be uploaded in crop_image folder. And lastly send response to Ajax request in Ajax format.

app/Http/Controllers/ImageCropController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageCropController extends Controller
{
    function index()
    {
     return view('image_crop');
    }

    function upload(Request $request)
    {
     if($request->ajax())
     {
      $image_data = $request->image;
      $image_array_1 = explode(";", $image_data);
      $image_array_2 = explode(",", $image_array_1[1]);
      $data = base64_decode($image_array_2[1]);
      $image_name = time() . '.png';
      $upload_path = public_path('crop_image/' . $image_name);
      file_put_contents($upload_path, $data);
      return response()->json(['path' => '/crop_image/' . $image_name]);
     }
    }
}



Create View Blade File


In Laravel framework, View Blade file has been used for display HTML output on web page. View file has been store under resources/views folder. Here we have make image_crop.blade.php file for this tutorial. In this file we have use Croppie plugin, Bootstrap library and jquery library.

resources/views/image_crop.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to Crop And Upload Image in Laravel 6 using jQuery Ajax</title>
  <script src="{{ asset('js/jquery.min.js') }}"></script>
  <link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}" />
    <link rel="stylesheet" href="{{ asset('css/croppie.min.css') }}" />
  <!--<script src="{{ asset('js/bootstrap.min.js') }}"></script>!-->
    <script src="{{ asset('js/croppie.min.js') }}"></script>
 </head>
 <body>
  <div class="container">    
    <br />
        <h3 align="center">How to Crop And Upload Image in Laravel 6 using jQuery Ajax</h3>
      <br />
      <div class="card">
        <div class="card-header">Crop and Upload Image</div>
        <div class="card-body">
          <div class="form-group">
            @csrf
            <div class="row">
              <div class="col-md-4" style="border-right:1px solid #ddd;">
                <div id="image-preview"></div>
              </div>
              <div class="col-md-4" style="padding:75px; border-right:1px solid #ddd;">
                <p><label>Select Image</label></p>
                <input type="file" name="upload_image" id="upload_image" />
                <br />
                <br />
                <button class="btn btn-success crop_image">Crop & Upload Image</button>
              </div>
              <div class="col-md-4" style="padding:75px;background-color: #333">
                <div id="uploaded_image" align="center"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <br />
          <br />
          
          <br />
          <br />
    </div>
 </body>
</html>

<script>  
$(document).ready(function(){
  
  $image_crop = $('#image-preview').croppie({
    enableExif:true,
    viewport:{
      width:200,
      height:200,
      type:'circle'
    },
    boundary:{
      width:300,
      height:300
    }
  });

  $('#upload_image').change(function(){
    var reader = new FileReader();

    reader.onload = function(event){
      $image_crop.croppie('bind', {
        url:event.target.result
      }).then(function(){
        console.log('jQuery bind complete');
      });
    }
    reader.readAsDataURL(this.files[0]);
  });

  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type:'canvas',
      size:'viewport'
    }).then(function(response){
      var _token = $('input[name=_token]').val();
      $.ajax({
        url:'{{ route("image_crop.upload") }}',
        type:'post',
        data:{"image":response, _token:_token},
        dataType:"json",
        success:function(data)
        {
          var crop_image = '<img src="'+data.path+'" />';
          $('#uploaded_image').html(crop_image);
        }
      });
    });
  });
  
});  
</script>


Set Route


In Laravel framework, we have to set the route of Controller class method. For this we have to open routes/web.php. In this file we have to set the route of this Controller class method.

routes/web.php

Route::get('image_crop','ImageCropController@index');

Route::post('image_crop/upload', 'ImageCropController@upload')->name('image_crop.upload');


Run Laravel Application


For Run Laravel web application, we have to go command prompt and write following command.


php artisan serve


This command will start Laravel server and give you Laravel application base url. For check above code, you to enter http://127.0.0.1:8000/image_crop url, then after you can check above code. So, this is complete step by step process of image preview for crop image using jQuery Croppie plugin before uploading of image by using Ajax in Laravel 6 framework. If you want to get complete source code file, you can free email us at webslesson@gmail.com. We will send you source code file in zip folder.


Thursday, 2 August 2018

Ajax File Upload with Progress Bar using PHP JQuery

Upload of Image or File must always required a Progress bar. This type of website feature which has been ignored by most of the web developers. This type of feature is an one part of web application functionality. If we have not use progress bar in image or file upload using Ajax then user cannot seen what is uploading which we have done in back end and he cannot get idea about file or image has been uploaded or not.

So, if user has send request to server for upload file or image operation, then it is best practice to see them about the progress of their uploading. Display of uploading process in progress bar, it is a good sign of our website UI/UX. For improving our web application UI/UX then we have to display upload process in progress bar and user can get idea about upload operation in process or has been completed. We have already publish how to upload Image using Ajax with PHP, but there is only we have simply upload image to folder without displaying of upload process in progress bar. But in this post we have learn how can we create animated progress bar using Jquery with Bootstrap while uploading of an image via Ajax.

For Select Image or File from our local computer here we have use A file input html tag and after this we have send this file to PHP using Ajax. Once it has send file upload request to PHP, then in Ajax script will execute Jquery animation using animate() method and display file uploading process in progress bar which has been make by using Bootstrap. Bootstrap progress bar will display process of uploading using JQuery animation. Here we have also use Jquery Form plugin has been used for handle upload Image via Ajax with progress bar.










Image / File Upload HTML Form


On index.php page we have make one HTML form with Input file tag. So user can select file from their local computer and send file data by sending form using Ajax. For send form data in this page we have already included Jquery Form plugin at the starting of script. We have use HTML 5 file accept attribute for select only .jpg and .png file.


<!DOCTYPE html>
 <html>
 <head>
  <title></title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <script src="js/jquery-1.10.2.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jquery.form.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Ajax File Upload Progress Bar using PHP JQuery</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading"><b>Ajax File Upload Progress Bar using PHP JQuery</b></div>
    <div class="panel-body">
     <form id="uploadImage" action="upload.php" method="post">
      <div class="form-group">
       <label>File Upload</label>
       <input type="file" name="uploadFile" id="uploadFile" accept=".jpg, .png" />
      </div>
      <div class="form-group">
       <input type="submit" id="uploadSubmit" value="Upload" class="btn btn-info" />
      </div>
      <div class="progress">
       <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
      </div>
      <div id="targetLayer" style="display:none;"></div>
     </form>
     <div id="loader-icon" style="display:none;"><img src="loader.gif" /></div>
    </div>
   </div>
  </div>
 </body>
</html>


JQuery Progress bar with Ajax Form Submit


In this example we have use Jquery Form library for submit form data using Ajax with JQuery Bootstrap animated progress bar. The ajaxSubmit() function has been used for submit image file to the PHP script via Ajax. Image Upload progress has been display in progress bar using uploadProgress callback function and by using Jquery animate() method we have use for display upload progress in progress bar.


<script>
$(document).ready(function(){
 $('#uploadImage').submit(function(event){
  if($('#uploadFile').val())
  {
   event.preventDefault();
   $('#loader-icon').show();
   $('#targetLayer').hide();
   $(this).ajaxSubmit({
    target: '#targetLayer',
    beforeSubmit:function(){
     $('.progress-bar').width('50%');
    },
    uploadProgress: function(event, position, total, percentageComplete)
    {
     $('.progress-bar').animate({
      width: percentageComplete + '%'
     }, {
      duration: 1000
     });
    },
    success:function(){
     $('#loader-icon').hide();
     $('#targetLayer').show();
    },
    resetForm: true
   });
  }
  return false;
 });
});
</script>


PHP Code for File Upload


This is simple PHP file upload script for upload file in specified location folder. Here All file data has been stored into $_FILES superglobal variable of PHP. For upload file to specified upload folder we have use PHP move_uploaded_file() function.


<?php

//upload.php

if(!empty($_FILES))
{
 if(is_uploaded_file($_FILES['uploadFile']['tmp_name']))
 {
  sleep(1);
  $source_path = $_FILES['uploadFile']['tmp_name'];
  $target_path = 'upload/' . $_FILES['uploadFile']['name'];
  if(move_uploaded_file($source_path, $target_path))
  {
   echo '<img src="'.$target_path.'" class="img-thumbnail" width="300" height="250" />';
  }
 }
}

?>


If you have follow this source code then you can make Ajax Image upload with Progress bar in PHP script. If you want to download source code click on below link.