Laravel 6 - Preview and Crop Image Before Upload using Ajax

  • 02-04-2022
  • 2585
  • Laravel 6
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

A few days ago I was work on the Laravel 6 application. Then I need to create an image upload on the profile page section. In this task first thing image preview then crop and save an image directory. So, I was thinking about this task what can I do for this task. I know very well Laravel image uploads simple way to image upload. But, I need to create Preview and Crop Image Before Upload.

I thought why not use Jquery make it manual. But it takes time and a large amount of code. Then I was decided on how to create a quick way. I know many several ways to make this task but I was thinking about how to make it very easy. So, I searched on google and find out the solution I show many demos and code but I have found it's very easy to use.

I found the best way in google search is croppie Jquery plugin with this help, We can do this task very easily. And I have seen many functions on its website, with the help of which you can make the best example and you can customize to your requirements.

So, Let's do this task.

Laravel 6 - Preview and Crop Image Before Upload using Ajax

Step 1: Create Routes in web.php file

In this first step, we need to create routes to the web.php file. So, let's create it.

routes/web.php

Route::get('crop-image', ['as' => 'image', 'uses' => 'ImageController@imageCreate']);
Route::post('crop-image-store', ['as'=>'upload.image','uses'=>'ImageController@ImageUpload']);

Step 2 : Create ImageController

Here, Create Controller to the following command. So, open your terminal and fire below command.

php artisan make:controller ImageController

After creating the Image Controller we follow ImagerController file code.

App/Http/Controllers/ImageController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ImageController extends Controller
{

    public function imageCreate(){

      return view('Uploadimage');

    }

    public function ImageUpload(Request $request)
    {

        $image = $request->image;

        list($type, $image) = explode(';', $image);
        list(, $image)      = explode(',', $image);

        $image = base64_decode($image);
        $image_name= time().'.png';
        $path = public_path('image/'.$image_name);

        file_put_contents($path, $image);

        return response()->json(['status'=>true]);

    }

}

Step 3: Create Uploadimage.blade.php file

In the last step, we need to create a blade file. So, let's do it.

resources/views/Uploadimage.blade.php

<html lang="en">
<head>
  <title>Laravel 6 - Preview and Crop Image Before Upload using Ajax- webappfix.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.js"></script>
  <meta name="token" content="{{ csrf_token() }}">
</head>
<body>
    <div class="container">
      <div class="panel panel-info">
        <div class="panel-heading">Laravel 6 - Preview and Crop Image Before Upload using Ajax- webappfix.com</div>
        <div class="panel-body">
          <div class="row">
            <div class="col-md-4 text-center">
                <div id="upload-demo"></div>
            </div>
            <div class="col-md-4" style="padding:5%;">
                <strong>Select image for crop:</strong>
                <input type="file" id="images" name="image">
                <button class="btn btn-primary btn-block image-upload" style="margin-top:2%">Upload Image</button>
            </div>
            <div class="col-md-4">
                <div id="show-crop-image" style="background:#e2e2e2;width:400px;padding:60px 60px;height:400px;"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

   <script type="text/javascript">
    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="token"]').attr('content')
      }
    });

    var resize = $('#upload-demo').croppie({
        enableExif: true,
        enableOrientation: true,    
        viewport: { 
            width: 300,
            height: 300,
            type: 'circle'
        },

        boundary: {
            width: 300,
            height: 300
        }
    });

    $('#images').on('change', function () { 
      var reader = new FileReader();
        reader.onload = function (e) {
          resize.croppie('bind',{
            url: e.target.result
          }).then(function(){
            console.log('success bind image');
          });

        }
        reader.readAsDataURL(this.files[0]);
    });

    $('.image-upload').on('click', function (ev) {
      resize.croppie('result', {
        type: 'canvas',
        size: 'viewport'

      }).then(function (img) {
        $.ajax({
          url: "{{route('upload.image')}}",
          type: "POST",
          data: {"image":img},
          success: function (data) {
            html = '<img src="' + img + '" />';
            $("#show-crop-image").html(html);
          }
        });
      });
    });
 </script>
</body>
</html>

Now we require to create an image folder in public directory.

Now we are ready to run.

You can also visit croppie website Croppie


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :