How To Crop Image Before Upload in Laravel 10 Using Croppie.js

Reading Time: 6 minutes
360 Views

Inside this article we will see the concept of How To Crop Image Before Upload in Laravel 10 Using Croppie.js. Article contains classified information about image cropping and save to application.

In this tutorial we will use a jquery plugin Croppie.js. This plugin uses a CSS and JS file. Either you can use these plugin files via CDN link or by putting them into your application /public folder.

This tutorial will be very interesting to see and super easy to implement.

Read More: Laravel 10 How To Create Signature Pad Using jQuery

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Images Folder

Go to /public folder available at application root. Create a folder with name images. We will save generated signature images inside it.

Make sure images folder should have sufficient permission to write content into it.

Read More: SweetAlert2 jQuery Notification Plugin in Laravel 10 Tutorial

Create Controller

Open project into terminal and run this command into it.

$ php artisan make:controller ImageController

It will create ImageController.php file inside /app/Http/Controllers folder. Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageController extends Controller
{
    /**
     * Show the application view.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageCrop()
    {
        return view('image-crop');
    }
    /**
     * Submit image upload.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageCropPost(Request $request)
    {
        $data = $request->image;

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

        $data = base64_decode($data);
        $image_name = time() . '.png';
        $path = public_path() . "/images/" . $image_name;

        file_put_contents($path, $data);

        return response()->json(['status' => 1, 'message' => "Image uploaded successfully"]);
    }
}

Create Blade Layout File

Go to /resources/views folder and create a file with name image-crop.blade.php

Open image-crop.blade.php and write this complete code into it.

<html lang="en">

<head>
    <title>How To Crop Image Before Upload in Laravel 10 Using Croppie.js</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css">
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>


<body>
    <div class="container" style="margin-top:30px;">
        <div class="panel panel-primary">
            <div class="panel-heading">How To Crop Image Before Upload in Laravel 10 Using Croppie.js</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-4 text-center">
                        <div id="cropie-demo" style="width:250px"></div>
                    </div>
                    <div class="col-md-4" style="padding-top:30px;">
                        <strong>Select Image:</strong>
                        <input type="file" id="upload">
                        <br />
                        <button class="btn btn-success upload-result">Upload Image</button>
                    </div>


                    <div class="col-md-4">
                        <div id="image-preview"
                            style="background:#e1e1e1;padding:30px;height:200px;"></div>
                    </div>
                </div>


            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.js"></script>

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

        $uploadCrop = $('#cropie-demo').croppie({
            enableExif: true,
            viewport: {
                width: 200,
                height: 200,
                type: 'circle'
            },
            boundary: {
                width: 300,
                height: 300
            }
        });


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


        $('.upload-result').on('click', function(ev) {
            $uploadCrop.croppie('result', {
                type: 'canvas',
                size: 'viewport'
            }).then(function(resp) {
                $.ajax({
                    url: "{{ route('imageCrop') }}",
                    type: "POST",
                    data: {
                        "image": resp
                    },
                    success: function(data) {
                        html = '<img src="' + resp + '" />';
                        $("#image-preview").html(html);
                    }
                });
            });
        });

    </script>

</body>

</html>

Read More: Bootstrap Growl jQuery Notification Plugin in Laravel 10

Add Route

Open web.php file from /routes folder. Add these routes into it.

//...

use App\Http\Controllers\ImageController;

//...

Route::get('image-crop', [ImageController::class, "imageCrop"]);
Route::post('image-crop', [ImageController::class, "imageCropPost"])->name("imageCrop");

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/image-crop

When we hit Upload button, it will save the cropped image into images folder and also create a image preview at the right sided area.

We hope this article helped you to learn How To Crop Image Before Upload in Laravel 10 Using Croppie.js in a very detailed way.

Read More: How To Disable RSS Feed URLs in WordPress Website Tutorial

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more