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.


3 comments:

  1. laravel and ajax crud my edit function is not working please send me the tutorial on my email : ah.khan.ahzai@gmail.com

    ReplyDelete
  2. i needed croppie.css and croppie.min.js file

    ReplyDelete