Image Crop with Laravel5.4 Intervention and CropperJS jQuery

Image Crop with Laravel5.4 Intervention and CropperJS jQuery

CropperJS is a fast, easy to use image cropping plugin with tons of configuration options. Today i will told you how to crop and image with laravel intervention and CropperJS jQuery plugin.

First step is to Install Intervention Image

The best way to install Intervention Image is quickly and easily with Composer.
To install the most recent version, run the following command.

composer require intervention/image /// OR 
"intervention/image": "^2.3", // Add this to composer.json and run composer update

Integration in Laravel

Intervention Image has optional support for Laravel and comes with a Service Provider and Facades for easy integration.

Just see the instructions below.

After you have installed Intervention Image, open your Laravel config file config/app.php and add the following lines.

In the $providers array add the service providers for this package.

Intervention\Image\ImageServiceProvider::class

Add the facade of this package to the $aliases array.

‘Image’ => Intervention\Image\Facades\Image::class

Now the Image Class will be auto-loaded by Laravel.

Cropper.js

Quick start

Four quick start options are available:

  • Download the latest release.
  • Clone the repository: git clone https://github.com/fengyuanchen/cropperjs.git.
  • Install with NPMnpm install cropperjs.
  • Install with Bowerbower install cropperjs.

Installation

Include files:

<link  href="/path/to/cropper.css" rel="stylesheet">
<script src="/path/to/cropper.js"></script>

Implementation Cropper.JS With Laravel and Bootstrap Modal

1 . HTML

<div id="myModal" class="modal fade" role="dialog">
<div id="myModal" class="modal fade" role="dialog">  
<div class="modal-dialog">
    <!-- Modal content-->    
<div class="modal-content">     
  <div class="modal-header">       
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Image Upload</h4> 
  </div>      
<div class="modal-body">
         <img width="100%"  src="" id="image_cropper">
          <p class="text-center">   
          <button type="button" class="btn btn-primary rotate" data-method="rotate" data-option="-30"><i class="fa fa-undo"></i></button>                      
          <button type="button" class="btn btn-primary rotate" data-method="rotate" data-option="30"><i class="fa fa-repeat"></i></button> </p>            
</div>      
<div class="modal-footer"> 
    <input type="button" class="btn btn-primary" id="Save" value="Save">  </button>        
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>      
</div>    
</div>
</div>
</div>
<!-- File Upload Button -->
<form id="FileUpload" action="" method="post" enctype="multipart/form-data"> 
   <input type="hidden" name="cropped_value" id="cropped_value" value=""> 
   <input type="file" name="file" id="cropper" />
</form>

2. Javascript/Jquery

$(function() {
/////// Cropper Options set 
var cropper;
 var options = {
     aspectRatio: 1 / 1,
     minContainerWidth: 570,
     minContainerHeight: 350,
     minCropBoxWidth: 145,
     minCropBoxHeight: 145,
     rotatable: true,
     cropBoxResizable: false,
     crop: function(e) {
        $("#cropped_value").val(parseInt(e.detail.width) + "," + parseInt(e.detail.height) + "," + parseInt(e.detail.x) + "," + parseInt(e.detail.y) + "," + parseInt(e.detail.rotate));
     }
 };
///// Show cropper on existing Image
$("body").on("click", "#image_source", function() {
    var src = $("#image_source").attr("src");
    src = src.replace("/thumb", "");
    $('#image_cropper').attr('src', src);
    $('#image_edit').val("yes");
    $("#myModal").modal("show");
});
///// Destroy Cropper on Model Hide
$(".modal").on("hide.bs.modal", function() {
  $(".cropper-container").remove();
  cropper.destroy();
});
/// Show Cropper on Model Show
 $(".modal").on("show.bs.modal", function() {
    var image = document.getElementById('image_cropper');
    cropper = new Cropper(image, options);
});
///// Rotate Image 
$("body").on("click", ".rotate", function() {
     var degree = $(this).attr("data-option");
     cropper.rotate(degree);
 });
///// Saving Image with Ajax Call
$("body").on("click", "#Save", function() {
    var form_data = $('#FileUpload')[0];
    $.ajax({
        url: "<?php echo url('updatePhoto'); ?>", // Url to which the request is send
        type: "POST",
        mimeType: "multipart/form-data",
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }, // Type of request to be send, called as method
        data: new FormData(form_data), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false, // The content type used when sending data to the server.
        cache: false, // To unable request pages to be cached
        processData: false, // To send DOMDocument or non processed data file it is set to false
        success: function(res) // A function to be called if request succeeds
        {
          console.log("Image Crop with Laravel5.4 Intervention and CropperJS jQuery Success");
        }
    });
 });

////// When user upload image 
$(document).on("change", "#cropper", function() {
     var imagecheck = $(this).data('imagecheck'),
     file = this.files[0],
     imagefile = file.type,
     _URL = window.URL || window.webkitURL;
     img = new Image();
     img.src = _URL.createObjectURL(file);
     img.onload = function() {
     var match = ["image/jpeg", "image/png", "image/jpg"];
     if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {
        alert('Please Select A valid Image File');
        return false;
     } else {
       var reader = new FileReader();
       reader.readAsDataURL(file);
       reader.onloadend = function() { // set image data as background of div
       $(document).find('#image_cropper').attr('src', "");
       $(document).find('#image_cropper').attr('src', this.result);
       $('#image_edit').val("")
       $("#myModal").modal("show");
     }
   }
  }
  });
});

3. PHP Laravel Code

use Image;  /// top of controller

function to upload file in laravel with intervention

public function update_photo_crop(Request $request) {
    $cropped_value = $request->input("cropped_value"); //// Width,height,x,y,rotate for cropping
    $cp_v = explode("," ,$cropped_value); /// Explode width,height,x etc
    $file = Input::file('file'); 
    $file_name ="image.jpg";
    if (Input::hasFile('file')) {
       $path = $file->storeAs("original/path/" , $file_name); // Original Image Path 
       $img = Image::make($file->getRealPath());
       $path2 = public_path("file/path/$file_name"); ///  Cropped Image Path
       $img->rotate($cp_v[4] * -1);  /// Rotate Image
       $img->crop($cp_v[0],$cp_v[1],$cp_v[2],$cp_v[3])->save($path2); // Crop and Save
       echo "success";
    }
}

That’s all.

Muhammad Arfan

Muhammad Arfan

Web & Application Developer
PHP/MySql, Laravel5.x, Codeigniter, Rest APIs, Angular JS, VueJS, WordPressContact

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *