How to Crop an Image Before Uploading in LARAVEL 10

Spread the love

Hello Guys,

Are you wondering how to crop an image before uploading in Laravel 10? This tutorial will guide you through the process, showcasing the use of Cropper.js, a powerful JavaScript tool. Let’s delve into the world of image cropping in Laravel 10 and how to make the most of it.

Introduction:

Laravel 10 simplifies the task of cropping images before uploading, thanks to the integration of Cropper.js, an open-source JavaScript library. In this tutorial, we’ll not only explore the capabilities of Cropper.js but also demonstrate how you can leverage it in Laravel 10 to enhance your web applications.

Why Cropper.js?

Cropper.js provides an intuitive, customizable interface for cropping images. This JavaScript tool empowers developers to seamlessly incorporate image cropping features into their web applications. With Cropper.js, you can crop images to specific sizes, adjust aspect ratios, zoom in and out, rotate images, and even crop using various shapes like rectangles, circles, and ellipses. It’s a versatile solution that can elevate the functionality of your web app.

Tutorial Overview:

In this tutorial, we’ll walk you through the process of creating a media table with a name column in Laravel 10. What sets this tutorial apart is that, upon selecting an image, a modal window equipped with the Cropper.js plugin will pop up, allowing you to edit and save the image with ease. After saving the cropped image, we’ll also cover how to store it in both a database and a designated folder.

By the end of this tutorial, you’ll have a solid understanding of how to integrate Cropper.js into Laravel 10, enabling you to crop images effectively before uploading. Say goodbye to complex image editing procedures and hello to a seamless, user-friendly experience.

So, are you ready to enhance your Laravel 10 application with image cropping capabilities? Let’s get started!

Let’s now look at the straightforward procedure for finishing this example of Crop an Image Before Uploading.

Create Controller

In this stage, we will create a fresh CropImageController dedicated to handling store images. Within this controller, we will introduce two essential methods: index() and store(). To get started, execute the following command to generate this new controller.

php artisan make:controller CropImageController

Confirm that the ‘uploads‘ folder within the public directory has the necessary permissions. This step is crucial for storing images in that folder.

app/Http/Controllers/CropImageController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use App\Models\Media;
  
class CropImageController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('cromImage');
    }
        
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
                'image_base64' => 'required',
            ]);
      
        $input['name'] = $this->storeBase64($request->image_base64);
        Media::create($input);
            
        return back()->with('success', 'Image uploaded successfully.');
    }
    /**
     * Write code on Method
     *
     * @return response()
     */
    private function storeBase64($imageBase64)
    {
        list($type, $imageBase64) = explode(';', $imageBase64);
        list(, $imageBase64)      = explode(',', $imageBase64);
        $imageBase64 = base64_decode($imageBase64);
        $imageName= time().'.png';
        $path = public_path() . "/uploads/" . $imageName;
  
        file_put_contents($path, $imageBase64);
          
        return $imageName;
    }
}

Create Routes

To efficiently handle GET and POST requests for call views and image storage, you can optimize your website’s routes in the web.php file. Here’s how to do it:

  1. Open the web.php file in your Laravel project.
  2. Add the necessary routes for managing GET and POST requests related to call views and image storage.

Also Read: How to use One to One Relationship in LARAVEL 10

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\CropImageController;
  
/* 
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('crop-image-upload', [CropImageController::class, 'index']);
Route::post('crop-image-upload', [CropImageController::class, 'store'])->name('crop.image.upload.store');

Create Blade File

Now that we’ve established this file, we’ll craft a fundamental Bootstrap form integrated with cropper.js for image cropping. Let’s proceed to generate the subsequent file:

resources/views/cromImage.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Crop Image Before Upload Example - itcodestuff.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 - itcodestuff.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 - itcodestuff.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> 

Now, Enter the provided URL into your web browser to view the app’s output.

Also Read: How to use Try Catch Exception Handling in API Using laravel 10

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

Explore our Laravel blog section for insightful content and helpful tips.

Leave a Comment