Laravel – Crop and upload an image with jQuery Croppie plugin using Ajax

By | August 7, 2018
Laravel - Crop and upload an image with jQuery Croppie plugin

Hello friends,

We generally need to crop and upload image in our application. So in this article i will let you know Laravel – Crop and upload an image with jQuery Croppie plugin. It is very easy to integrate in your laravel or php application.

In this article i will use croppie jquery plugin to get the image crop feature. It also provides zooming feature so you can zoom an image then according to your choice you can choose particular part of the image to crop and upload

Jquery Croppie plugin also provides image re-sizing feature.

So lets’s start the steps to integrate crop and upload image feature in our application.

Let’s assume you have already installed laravel application. Create ImageCropController.php file in your application’s controller directory and copy the below code into this file.

app/Http/Controllers/ImageCropController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageCropController extends Controller
{
    public function index(){
    	return view('image_handling.crop_image');
    }

    public function imageCrop(Request $request){
    	$image_file = $request->image;
    	list($type, $image_file) = explode(';', $image_file);
        list(, $image_file)      = explode(',', $image_file);
        $image_file = base64_decode($image_file);
        $image_name= time().'_'.rand(100,999).'.png';
        $path = public_path('uploads/'.$image_name);

        file_put_contents($path, $image_file);
        return response()->json(['status'=>true]);
    }
}

And after creating the controller file in the second step create view file.  Here i am creating a directory(image_handling) to separate the crop view file and a blade file to choose and crop a file.

So simply create crop_image.blade.php file and copy the below code into this file

crop_image.blade.php

@extends('layouts.app')
@section('content')
  <link rel="stylesheet" href="{{ asset('css/croppie.min.css') }}">
  <script src="{{ asset('js/croppie.js') }}"></script>

  <div class="panel panel-info">
    <div class="panel-heading">Laravel - Crop and upload an image with jQuery Croppie plugin using Ajax</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>Choose image to crop:</strong>
        <input type="file" id="image_file">

        <button class="btn btn-primary btn-block upload-image" style="margin-top:2%">Upload Image</button>
        <div class="alert alert-success" id="upload-success" style="display: none;margin-top:10px;"></div>
        </div>

        <div class="col-md-4">
        <div id="preview-crop-image" style="background:#9d9d9d;width:300px;padding:50px 50px;height:300px;"></div>
        </div>
      </div>

    </div>
  </div>


<script type="text/javascript">

$.ajaxSetup({
headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});


var resize = $('#upload-demo').croppie({
    enableExif: true,
    enableOrientation: true,    
    viewport: { // Default { width: 100, height: 100, type: 'square' } 
        width: 200,
        height: 200,
        type: 'circle' //square
    },
    boundary: {
        width: 300,
        height: 300
    }
});


$('#image_file').on('change', function () { 
  var reader = new FileReader();
    reader.onload = function (e) {
      resize.croppie('bind',{
        url: e.target.result
      }).then(function(){
        console.log('jQuery bind complete');
      });
    }
    reader.readAsDataURL(this.files[0]);
});


$('.upload-image').on('click', function (ev) {
  resize.croppie('result', {
    type: 'canvas',
    size: 'viewport'
  }).then(function (img) {
    html = '<img src="' + img + '" />';
    $("#preview-crop-image").html(html);
    $("#upload-success").html("Images cropped and uploaded successfully.");
    $("#upload-success").show();
    // $.ajax({
    //   url: "{{route('croppie.upload-image')}}",
    //   type: "POST",
    //   data: {"image":img},
    //   success: function (data) {
        
    //   }
    // });
  });
});


</script>


@endsection

Now in the next and last step create routes to handle the crop feature in your application.

Add the following routes into Routes/web.php file

Route::get('crop-image', 'ImageCropController@index');
Route::post('crop-image', ['as'=>'croppie.upload-image','uses'=>'ImageCropController@imageCrop']);

After following the above steps you have successfully integrated crop and upload feature with croppie plugin into your laravel application.

Please feel free to comment if you have any query/question regarding this article.


Show Demo