Blog

Laravel – Crop and upload an image with jQuery Croppie

We generally need to crop and upload images in our application Or want to store the cropped image in the folder and database.

Using croppie js we can easily crop images before uploading.

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

1. Add Routes

Route::post('crop-image-upload ', 'CropImageController@ uploadCropImage')->name('cropImageUpload');

2. Add Blade View File

  • Add following code into your blade file for image field

    @section('content')
    
    &ltdiv class="content-wrapper"&gt
        &ltsection class="content"&gt
            &ltdiv class="row"&gt
                &ltform class="" id="" role="form" action="{{route('cropImageUpload')}}" method="post" enctype="multipart/form-data" &gt
                    {{ csrf_field() }}
                    &ltdiv class="col-sm-12"&gt
                        &ltdiv class="box box-primary"&gt
                            &ltdiv class="box-body"&gt
                              &ltdiv class="form-group"&gt
                                  &ltlabel for="" class="control-label post_data_label" &gtUpload Image&lt/label&gt&ltspan class="colorRed"&gt *&lt/span&gt &ltspan class="pull-right"&gt&lti&gt(Resolution : 480px * 270px)&lt/i&gt&lt/span&gt&ltbr&gt
                                  &ltdiv class="vc_column-inner "&gt
                                      &ltlabel class="cabinet center-block"&gt
                                          &ltfigure&gt
                                              &ltimg src="{{ URL::asset('/resources/assets/img/default.png')}}" class="gambar" id="item-img-output"  name="avatar"/&gt
                                          &lt/figure&gt
                                          &ltp&gt&lt/p&gt
                                          &ltinput type="hidden" name="main_image" value="" id="main_image" style=""&gt
                                          &ltinput type="file" accept="image/png, image/jpeg, image/jpg" class="item-img file center-block" name="file_photo"/&gt
                                      &lt/label&gt
    
                                      &ltdiv class="modal fade" id="cropImagePop" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt
                                          &ltdiv class="modal-dialog  "&gt
                                              &ltdiv class="modal-content"&gt
                                                  &ltdiv class="modal-body"&gt
                                                      &ltdiv id="upload-demo" class="center-block"&gt&lt/div&gt
                                                  &lt/div&gt
                                                  &ltdiv class="modal-footer"&gt
                                                      &ltbutton type="button" class="btn btn-default close_crop" id="cancelCropBtn" data-dismiss="modal"&gtClose&lt/button&gt
                                                      &ltbutton type="button" class="btn btn-default" id="Flip"&gtFlip&lt/button&gt
                                                      {{-- &ltbutton class="btn btn-default" id="rotate" data-deg="-90"&gtRotate&lt/button&gt --}}
                                                      &ltbutton type="button" id="cropImageBtn" class="btn btn-primary"&gtCrop&lt/button&gt
                                                  &lt/div&gt
                                              &lt/div&gt
                                          &lt/div&gt
                                      &lt/div&gt
                                  &lt/div&gt
                                  {{-- &ltlabel for="" class="control-label post_data_label" &gtUpload Image&lt/label&gt&ltspan class="colorRed"&gt *&lt/span&gt&ltbr&gt
                                  &ltdiv class="" style="text-align:center"&gt
                                      &ltimg class="old_profile_imageSub" src="{{ URL::asset('/resources/assets/custom/default.png')}}" height="300" width="350"/&gt
                                  &lt/div&gt
                                  &ltinput required class="profile_image_showInput" type="file" id="main_image" name="main_image" accept="image/*" onchange="readURL(this);" aria-required="true" aria-label="Close" /&gt
                                  &ltspan class="changeImage profilechangeImage"&gt&lti class="fa fa-edit"&gt&lt/i&gt Click Here To Upload Image&lt/span&gt --}}
                              &lt/div&gt
                            &lt/div&gt
                        &lt/div&gt
                    &lt/div&gt
                    &ltdiv class="col-sm-12"&gt
                        &ltdiv class="box" style="border-top:0"&gt
                            &ltdiv class="box-footer"&gt
                                &ltbutton style="margin-left: 20px;" type="button" id="cancelBtn" class="btn btn-default pull-right"&gtCancel&lt/button&gt
                                &ltbutton type="submit" id="createBtn" class="btn btn-success pull-right" style="margin-left: 20px;"&gtCreate&lt/button&gt
                            &lt/div&gt
                        &lt/div&gt
                    &lt/div&gt
                &lt/form&gt
                &lt!-- /.col --&gt
            &lt/div&gt
        &lt/section&gt
    &lt/div&gt
    
    @endsection
    @section('css')
    &ltlink rel="stylesheet" href="{{ URL::asset('/resources/assets/custom/image_cropping/prism.css')}}"&gt
    &ltlink rel="stylesheet" href="{{ URL::asset('/resources/assets/custom/image_cropping/sweetalert.css')}}"&gt
    &ltlink rel="stylesheet" href="{{ URL::asset('/resources/assets/custom/image_cropping/croppie.css')}}"&gt
    &ltstyle&gt
        .profile_image_showInput {
            opacity: 1;
            cursor: pointer;
            display: block;
            margin-top: 15px;
            height: 30px;
            width: 100% ;
            background-color: #269abc;
        }
        .changeImage {
            background: #269abc none repeat scroll 0 0;
            border-radius: 0px;
            pointer-events: none;
            display: block;
            padding: 5px 15px;
            bottom: 0;
            color: #fff;
            margin-top: -30px ;
            margin: 0 auto;
            width: 100%;
            float: left;
            left: 0;
            position: relative;
            text-align: center;
        }
        body, html, #beacon_canvas, #map_canvas,#map_canvas2,#map_canvas1{
            /* position:absolute; */
            height: 250px;
            margin: 0;
        }
        #beacon_canvas .centerMarker, #map_canvas .centerMarker,#map_canvas2 .centerMarker2,#map_canvas1 .centerMarker1{
            position:absolute;
            /*url of the marker*/
            background:url('https://maps.gstatic.com/mapfiles/markers2/marker.png') no-repeat;
            /*center the marker*/
            top:50%;
            left:50%;
            z-index:1;
            /*fix offset when needed*/
            margin-left:-10px;
            margin-top:-34px;
            /*size of the image*/
            height:34px;
            width:20px;
            cursor:pointer;
        }
        #upload-demo{
            height: 500px;
        }
        .cabinet figure{
            text-align: center;
        }
        .old_profile_imageSub, #item-img-output{
            /* height: 100%; */
            max-width: 100%;
        }
        .control-label{
          display: inline-block;
        }
    &lt/style&gt
    @endsection
    @section('script')
    
    &ltscript src="{{URL::asset('resources/assets/custom/jQuery-validation-plugin/jquery.validate.js')}}"&gt&lt/script&gt
    &ltscript src="{{URL::asset('resources/assets/custom/jQuery-validation-plugin/additional-methods.js')}}"&gt&lt/script&gt
    &ltscript src="{{URL::asset('/resources/assets/custom/image_cropping/prism.js')}}"&gt&lt/script&gt
    &ltscript src="{{URL::asset('/resources/assets/custom/image_cropping/sweetalert.js')}}"&gt&lt/script&gt
    &ltscript src="{{URL::asset('/resources/assets/custom/image_cropping/croppie.js')}}"&gt&lt/script&gt
    &ltscript src="{{URL::asset('/resources/assets/custom/image_cropping/main.js')}}"&gt&lt/script&gt
    &ltscript src="{{URL::asset('/resources/assets/custom/image_cropping/exif.js')}}"&gt&lt/script&gt
    
    @endsection
    
  • Note that you need to include the css and javascript of Croppie into your blade file.

  • Then, include the following script code into your blade file

    &ltscript type="text/javascript"&gt
        // Start upload preview image
        var FLIP = 2;
        var NORMAL = 1;
        var orientation = NORMAL;
        var $uploadCrop1, tempFilename, rawImg, imageId;
        var fileTypes = ['jpg', 'jpeg', 'png'];
            function readFile(input) {
                if (input.files && input.files[0]) {
                        var reader = new FileReader();
                        var file = input.files[0]; // Get your file here
                        var fileExt = file.type.split('/')[1]; // Get the file extension
                        if (fileTypes.indexOf(fileExt) !== -1) {
                            reader.onload = function (e) {
                                $('.upload-demo').addClass('ready');
                                $('#cropImagePop').modal('show');
                                rawImg = e.target.result;
                            }
                            reader.readAsDataURL(input.files[0]);
    
                        }else{
                            swal("Only JPEG, PNG, JPG file types are supported");
                            $(".item-img").val("");
                        }
                    }
                    else {
                    swal("Please select an image");
                    $("#main_image").val("");
                    $("#item-img-output").attr("src",SITE_URL + "/resources/assets/custom/default.png");
    
                }
            }
            $uploadCrop1 = $('#upload-demo').croppie({
                viewport: {
                width: 480,
                height: 270,
                },
                enableOrientation: true,
                enforceBoundary: true,
                enableExif: true
            });
            $('#cropImagePop').on('shown.bs.modal', function(){
                $uploadCrop1.croppie('bind', {
                    url: rawImg
                    }).then(function(){
                        $("span#main_image-error").hide();
                    });
            });
            $('#Flip').click(function() {
                orientation = orientation == NORMAL ? FLIP : NORMAL;
                $uploadCrop1.croppie('bind', {
                    url: rawImg,
                    orientation: orientation,
                });
            });
            $('#rotate').click(function() {
                $uploadCrop1.croppie('rotate', parseInt($(this).data('deg')));
            });
            $('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
            $('#cancelCropBtn').data('id', imageId); readFile(this); });
            $("#cancelCropBtn").click(function(){
               $(".item-img").val("");
               $("#main_image").val("");
               $("#item-img-output").attr("src",SITE_URL + "/resources/assets/custom/default.png");
            });
            $('#cropImageBtn').on('click', function (ev) {
                $uploadCrop1.croppie('result', {
                type: 'base64',
                format: 'jpeg',
                size: {width: 480, height: 270}
                }).then(function (resp) {
                    $('#item-img-output').attr('src', resp);
                    $('#main_image').attr('value', resp);
                    $('#cropImagePop').modal('hide');
                });
            });
        // End upload preview image
    &lt/script&gt
    

3. Create Controller File

  • Add this code in your controller for upload file

    &lt?php
    
    namespace App\Http\Controllers\Admin;
    
    use App\Http\Controllers\Controller;
    use App\User;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Input;
    use Image;
    use File;
    use DB;
    use URL;
    use Yajra\DataTables\Facades\DataTables;
    use App\Helper\GlobalHelper;
    use Auth;
    use Intervention\Image\ImageManagerStatic as ImageResize;
    
    class CropImageController extends Controller
    {
        public function uploadCropImage(Request $request)
        {
            if(!empty($request->main_image) || $request->main_image != ''){
                $data = explode(';', $request->main_image);
                $part = explode("/", $data[0]);
                $image = $request->main_image;  // your base64 encoded
                $image = str_replace('data:image/'.$part[1].';base64,', '', $image);
                $image = str_replace(' ', '+', $image);
                $fileName = md5(microtime().str_random(10)) .'.'.$part[1];
                $destinationPath = base_path().'/resources/uploads/';
                \File::put(base_path().'/resources/uploads/' .$fileName, base64_decode($image));
                chmod($destinationPath.$fileName,0777);
                $image = url('/').'/resources/uploads/'.$fileName;
            }
             return response()->json(['status'=>true]);
        }
    }
    
  • After followed successfully you must have to create “upload” folder with full permissions

4. Now You can see image cropping

Lets Nurture

Share
Published by
Lets Nurture

Recent Posts

Best AI Web Design Tools In 2025 To Build Your Dream Website Faster

Web design was once an element of online brand-building that you needed to know how…

2 months ago

AI In Finance: How Machine Learning Is Transforming Banking

Financial services and banking are being reshaped and revolutionized by what artificial intelligence has made…

2 months ago

Can I Add Google Maps To My Android App: A Step-By-Step Integration Guide

Yes, you can add Google Maps to your Android app, providing seamless, interactive mapping for…

2 months ago

Future-Proof Your SEO: Top Digital Marketing Trends You Need To Leverage In 2025

SEO and digital marketing are constantly evolving. It happens slowly but quickly at the same…

2 months ago

The Ethics of AI: Balancing Innovation with Responsibility

As an AI development team, we regularly encounter scenarios and questions from clients regarding AI…

2 months ago

How AI-Powered Predictive Analytics Is Shaping Business Decisions

Predictive analytics is your ultimate guide to data-backed business strategy. Data-driven insights, proactive decision-making, and…

2 months ago