Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Crop Image Before Upload using Cropper JS Tutorial

Last Updated on May 18, 2024 by

Cropper JS is a library of JavaScript that allow users to crop or resize images on forms before uploading them to the server.

Let’s start by creating an image upload form, and add a cropper JS method to it that allows users to crop the image before upload on blade view forms in laravel 11:

Step 1: Create Image Upload Form

Create a form in your Blade view to upload an image and display the cropping feature:

<style>
    .image-upload-form {
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f9f9f9;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    font-weight: bold;
}

.form-control-file {
    display: block;
    width: 100%;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}

.image-preview-container {
    margin-top: 20px;
    text-align: center;
}

.image-preview {
    max-width: 100%;
    height: auto;
    margin-top: 10px;
}

.btn-primary {
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
}

.btn-primary:hover {
    background-color: #0069d9;
    border-color: #0062cc;
}

</style>
<form action="{{ route('crop.upload') }}" method="post" enctype="multipart/form-data" class="image-upload-form">
    @csrf
    <div class="form-group">
        <label for="image" class="form-label">Select Image:</label>
        <input type="file" name="image" id="image" class="form-control-file">
    </div>
    <div class="image-preview-container">
        <img id="preview" src="#" alt="Image Preview" class="image-preview">
    </div>
    <button type="submit" class="btn btn-primary">Upload</button>
</form>

Step 2: Set Up Cropper.js

Set up Cropper JS by including the following Cropper JS CSS and JS to the form:

<link href="https://cdn.jsdelivr.net/npm/cropperjs/dist/cropper.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/cropperjs/dist/cropper.min.js"></script>

Step 3: Initialize Cropper.js

Add JavaScript code to initialize Cropper.js and handle image crop functionality:

<script>
    const image = document.getElementById('image');
    const preview = document.getElementById('preview');
    
    image.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.addEventListener('load', function() {
                preview.src = reader.result;
                
                // Initialize Cropper.js
                const cropper = new Cropper(preview, {
                    aspectRatio: 1 / 1, // Set aspect ratio as needed
                    crop: function(event) {
                        // Output cropped area details
                        console.log(event.detail.x);
                        console.log(event.detail.y);
                        console.log(event.detail.width);
                        console.log(event.detail.height);
                    }
                });
            });
            reader.readAsDataURL(file);
        }
    });
</script>

Step 4: Handle Image Upload in Controller

In your Laravel controller, create an image upload method into it to handle cropped image upload:

use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

public function upload(Request $request)
{
    // Validate the uploaded file
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // Adjust file size as needed
    ]);

    // Get the uploaded image
    $image = $request->file('image');
    
    // Store the cropped image
    $croppedImage = Image::make($image)
        ->crop($request->input('width'), $request->input('height'), $request->input('x'), $request->input('y'))
        ->save(public_path('images/' . $image->hashName()));

    // Return a success response
    return response()->json(['success' => 'Image cropped successfully.']);
}

Step 5: Set Up Routes

Define a route to handle the image upload requests:

Route::get('/upload', function () {
    return view('upload');
});

Route::post('/crop/upload', [ImageController::class, 'upload'])->name('crop.upload');

To test this application, start the browser and type /upload in it.

Leave a Comment