Laravel 10 Crop Image Before Upload Using Cropper Js

Apr 06, 2024 | Laravel 10 Laravel


In this concise guide, we'll demonstrate how to implement image cropping before upload in Laravel 10 using Cropper.js. We'll discuss how to integrate Cropper.js into your Laravel 10 application to enable image cropping functionality.

Cropper.js is a powerful JavaScript library that facilitates image cropping with a user-friendly interface. It offers various features such as cropping images to specific dimensions or aspect ratios, zooming in and out, rotating images, and cropping using different shapes like rectangles, circles, and ellipses.

In our example, we'll start by creating a media table with a name column in the database. Then, we'll set up a simple form for image upload. Upon selecting an image, a modal will open using the Cropper.js plugin, allowing users to crop the image before saving. After saving, the cropped image will be stored in both the folder and the database.

Let's dive into the straightforward steps to accomplish this example.

Step 1: Create a New Laravel Project

If you haven't already, create a new Laravel project:

composer create-project laravel/laravel example-app
Step 2: Create a Database Migration and Model

Create a migration for the media table and a model for it:

php artisan make:migration create_media_table

Edit the migration file to include the necessary columns, such as name for storing the image name:

Schema::create('media', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

Run the migration:

php artisan migrate
Step 3: Set Up Routes

In routes/web.php, add routes to manage GET and POST requests for displaying the form and storing the image:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CropImageController;

Route::get('crop-image-upload', [CropImageController::class, 'index']);
Route::post('crop-image-upload', [CropImageController::class, 'store'])->name('crop.image.upload.store');
Step 4: Create the Controller

Generate a controller named app/Http/Controllers/CropImageController.php

php artisan make:controller CropImageController

Implement the index method to return the upload form view and the store method to handle the image upload and cropping.

Step 5: Create the View

Create a view file named resources/views/cromImage.blade.php with a form for image upload and a modal for cropping the image using Cropper.js. Include the necessary CSS and JS files for Bootstrap, Cropper.js, and jQuery.

Here's a simplified version of the view:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Crop Image Before Upload Example - ItErrorSolution.com</title>
    <meta name="_token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js"></script>
</head>
<style type="text/css">
    body{
        background: #f7fbf8; 
    }
    h1{
        font-weight: bold;
        font-size:23px;
    }
    img {
        display: block;
        max-width: 100%;
    }
    .preview {
        text-align: center;
        overflow: hidden;
        width: 160px; 
        height: 160px;
        margin: 10px;
        border: 1px solid red;
    }
    input{
        margin-top:40px;
    }
    .section{
        margin-top:150px;
        background:#fff;
        padding:50px 30px;
    }
    .modal-lg{
        max-width: 1000px !important;
    }
</style>
<body>
  
    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-2 section text-center">
                <h1>Laravel Crop Image Before Upload Example - ItErrorSolution.com</h1>
                <form action="{{ route('crop.image.upload.store') }}" method="POST">
                    @csrf
                    <input type="file" name="image" class="image">
                    <input type="hidden" name="image_base64">
                    <img src="" style="width: 200px;display: none;" class="show-image"> 
  
                    <br/>
                    <button class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
  
    <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalLabel">Laravel Crop Image Before Upload Example - ItErrorSolution.com</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="img-container">
                        <div class="row">
                            <div class="col-md-8">
                                <img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
                            </div>
                            <div class="col-md-4">
                                <div class="preview"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="crop">Crop</button>
                </div>
            </div>
        </div>
    </div>
  
    <script>
        var $modal = $('#modal');
        var image = document.getElementById('image');
        var cropper;
  
        /*------------------------------------------
        --------------------------------------------
        Image Change Event
        --------------------------------------------
        --------------------------------------------*/
        $("body").on("change", ".image", function(e){
            var files = e.target.files;
            var done = function (url) {
                image.src = url;
                $modal.modal('show');
            };
  
            var reader;
            var file;
            var url;
  
            if (files && files.length > 0) {
                file = files[0];
  
                if (URL) {
                    done(URL.createObjectURL(file));
                } else if (FileReader) {
                    reader = new FileReader();
                    reader.onload = function (e) {
                        done(reader.result);
                    };
                reader.readAsDataURL(file);
                }
            }
        });
  
        /*------------------------------------------
        --------------------------------------------
        Show Model Event
        --------------------------------------------
        --------------------------------------------*/
        $modal.on('shown.bs.modal', function () {
            cropper = new Cropper(image, {
                aspectRatio: 1,
                viewMode: 3,
                preview: '.preview'
            });
        }).on('hidden.bs.modal', function () {
            cropper.destroy();
            cropper = null;
        });
  
        /*------------------------------------------
        --------------------------------------------
        Crop Button Click Event
        --------------------------------------------
        --------------------------------------------*/
        $("#crop").click(function(){
            canvas = cropper.getCroppedCanvas({
                width: 160,
                height: 160,
            });
  
            canvas.toBlob(function(blob) {
                url = URL.createObjectURL(blob);
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onloadend = function() {
                    var base64data = reader.result; 
                    $("input[name='image_base64']").val(base64data);
                    $(".show-image").show();
                    $(".show-image").attr("src",base64data);
                    $("#modal").modal('toggle');
                }
            });
        });
          
    </script>
</body>
</html> 
Step 6: Implement JavaScript for Cropping

Use Cropper.js to allow users to crop the selected image. When the user clicks the "Crop" button, get the cropped image data and set it as the value of a hidden input field in the form. This data can then be sent to the server when the form is submitted.

Step 7: Run the Application

Start the Laravel development server:

php artisan serve

Access the image upload form by navigating in your web browser.

http://localhost:8000/crop-image-upload

This guide provides a basic overview of how to implement image cropping before upload in Laravel 10 using Cropper.js. Depending on your specific requirements, you may need to adjust the code to fit your application's structure and logic



Tags :
#Laravel 10
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"