Monday, January 20, 2020

Image Croping and uploading using jQUERY with Ajax in Laravel

Image Croping and uploading using jQUERY with Ajax in Laravel

Are you learning the Laravel framework for developing web applications? In this post you will find an interesting topic like "How to crop an image before loading it into the Laravel framework". Here we used the Laravel 6 framework to create these types of functions in any web-based application. If you would like to learn how to use Laraxel 6 to crop and load images using jQuery with Ajax, this publication provides an introduction to this topic.

Here we have the jQuery Croppie plugin, which is used to crop an image before loading. There are many jQuery add-ons on the internet for crop image, but here we used the croppie plug-in with Laravel 6 framework for crop image. Because it's often used to crop images and it's easy to learn how to crop images. If you want to add features like image cutting for your web application, you can use this add-on as it is very easy to integrate into our web application.

In summary, in this release we used the jQuery plugin to crop an image, and when we use Ajax we uploaded it to the web server using the Laravel 6 framework. After the page was loaded into the web browser, this croppie plug-in was initialized. After selecting the image of our local computer and then previewing the selected image, we can display it on the website. In this preview, we can also enlarge the image and drag the crop window viewport. In this tutorial you will then learn step by step how to crop an image with the Croppie plugin and then load a cropped image with Ajax with the Laravel 6-Frame.


  1.  Install Laravel 6 Framework by using command line
  2. Generate Controller
  3. Generate View Blade File
  4. Set Route
  5. Run Laravel 6 Application

Install Laravel 6 Framework by using command line


If you want to use the Laravel framework for a web development task, you must first download and install it on your local computer by using composer. To download the Laravel 6 framework, you need to go to the command prompt and to the directory where you want to download the Laravel framework. Then you need to run the following command at the command prompt.

composer create-project --prefer-dist laravel/laravel laravel6
This command creates the laravel6 folder and downloads the Laravel 6 framework under it.

 Generate Controller


After downloading the Laravel framework, you can use Laravel for web development. Here we want to run the driver class first to process the browser's http request. To create the controller class, you must go to the command prompt and execute the 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]);
     }
    }
}

 Generate View Blade File


As part of Laravel, the view blade file was used to display the HTML output on the website. The view file was saved in the "resources / views" folder. Here we have the file image_crop.blade.php for this tutorial. In this file we used the Croppie plugin, the Bootstrap library and the JQuery library.

resources/views/image_crop.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Image Croping and uploading using jQUERY with Ajax in Laravel</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">Image Croping and uploading using jQUERY with Ajax in Laravel</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 the framework of Laravel we have to define the method path of the controller class. For this we have to open routes / web.php. In this file we have to set the path of this driver 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 the Run Laravel web application, you must go to the command prompt and enter the following command.

php artisan serve
This command starts the Laravel server and provides you with the base URL of the Laravel application. To review the code above, enter the URL http://127.0.0.1:8000/image_crop. Then you can check the previous code. So, this is the step-by-step process of previewing the image to crop images using the jQuery Croppie plugin before loading the image using Ajax in the framework of Laravel 6.

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.