Crop and Upload image in laravel using jcrop js

When it comes to uploading images on your website, it is important to ensure that they are of appropriate size and resolution to avoid slowing down your website’s loading speed. One way to do this is by cropping the images before uploading them. Laravel, a popular PHP framework, makes it easy to implement image cropping functionality with the help of the Jcrop JavaScript library. In this article, we will guide you step-by-step on how to crop an image before uploading using Jcrop JS in Laravel, using a CDN.

Step 1: Set Up Your Laravel Project

To get started, you will need to have Laravel installed on your local machine or server. If you do not have it installed, you can download it from the official Laravel website. Once you have installed Laravel, create a new project and set up your development environment.

Read Also : Laravel crop image before upload using cropper js

Step 2: Install Jcrop JS Library

The next step is to install the Jcrop JS library. You can use a CDN (Content Delivery Network) to quickly and easily add the Jcrop JS library to your Laravel project. To do this, add the following code to the head section of your layout file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/js/jquery.Jcrop.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/css/jquery.Jcrop.min.css" />

Step 3: Create a Form to Upload the Image

Next, create a form to upload the image. You can use Laravel’s built-in form functionality to create a form. Add the following code to your blade file:

<form method="POST" action="{{ route('upload') }}" enctype="multipart/form-data">    @csrf    <input type="file" name="image">    <input type="submit" value="Upload"></form>

This form includes a file input that allows the user to select an image file to upload, and a submit button to submit the form to the server.

Step 4: Create a Route for the Upload Action

Create a route for the upload action. In your routes file, add the following code:

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

This code creates a route that points to the upload method of the ImageController class.

Step 5: Create a Controller for the Image Upload

Next, create a controller for the image upload. In your terminal, run the following command to create a new controller:

php artisan make:controller ImageController

This command will create a new controller file called ImageController.php in the app/Http/Controllers directory.

Step 6: Add the Upload Method to the Controller

Add the upload method to the ImageController. This method will handle the image upload and cropping. Add the following code to the upload method:

public function upload(Request $request){    $image = $request->file('image');    $filename = time() . '.' . $image->getClientOriginalExtension();    $image->move(public_path('uploads'), $filename);    $image_path = public_path('uploads') . '/' . $filename;    list($width, $height) = getimagesize($image_path);    return view('crop')->with('image_path', $image_path)                       ->with('image_width', $width)                       ->with('image_height', $height);}

This code gets the uploaded image file, generates a unique filename for it, moves it to the public/uploads directory, and then retrieves its path and dimensions. It then returns a view called crop with the image path and dimensions as variables.

Step 7: Create a View for the Cropping Interface

Create a view for the cropping interface. In your resources/views directory, create a new file called crop.blade.php and add the following code:

<div id="crop-container">    <img src="{{ asset($image_path) }}" id="crop-image"></div><form method="POST" action="{{ route('crop') }}">    @csrf    <input type="hidden" name="image_path" value="{{ $image_path }}">    <input type="hidden" name="image_width" value="{{ $image_width }}">    <input type="hidden" name="image_height" value="{{ $image_height }}">    <input type="hidden" name="crop_x" id="crop-x">    <input type="hidden" name="crop_y" id="crop-y">    <input type="hidden" name="crop_width" id="crop-width">    <input type="hidden" name="crop_height" id="crop-height">    <input type="submit" value="Crop"></form><script>    $(function() {        $('#crop-image').Jcrop({            aspectRatio: 1,            onSelect: updateCoords        });    });    function updateCoords(c) {        $('#crop-x').val(c.x);        $('#crop-y').val(c.y);        $('#crop-width').val(c.w);        $('#crop-height').val(c.h);    };</script>

This code creates a container for the image and a form that includes hidden inputs for the image path, width, and height, as well as the coordinates and dimensions of the cropped image. It also includes a script that initializes the Jcrop library and updates the hidden inputs with the selected coordinates and dimensions.

Step 8: Create a Route for the Crop Action

Create a route for the crop action. In your routes file, add the following code:

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

This code creates a route that points to the crop method of the ImageController class.

Step 9: Add the Crop Method to the Controller

Add the crop method to the ImageController. This method will handle the image cropping and saving. Add the following code to the crop method:

public function crop(Request $request){    $image_path = $request->input('image_path');    $image_width = $request->input('image_width');    $image_height = $request->input('image_height');    $crop_x = $request->input('crop_x');    $crop_y = $request->input('crop_y');    $crop_width = $request->input('crop_width');    $crop_height = $request->input('crop_height');    $image = Image::make($image_path);    $image->crop($crop_width,$crop_height, $crop_x, $crop_y);           $image->save();            $filename = basename($image_path);          $cropped_image_path = public_path('uploads/cropped/') . $filename;          $image->save($cropped_image_path);         return redirect('/')->with('success', 'Image cropped and saved successfully.');}

This code retrieves the input values for the image path, width, height, and crop coordinates and dimensions. It then loads the image using the Intervention Image library, crops it using the selected coordinates and dimensions, and saves it to the public/uploads/cropped directory with the same filename. Finally, it redirects back to the home page with a success message.

Step 10: Add Styling to the Cropping Interface

Add some styling to the cropping interface to make it look nicer. In your resources/views/crop.blade.php file, add the following CSS code:

#crop-container {	width: 500px;	height: 500px;	overflow: hidden;	margin: 0 auto;	position: relative;}#crop-image {	max-width: 100%;	max-height: 100%;	display: block;	position: absolute;	top: 50%;	left: 50%;	transform: translate(-50%, -50%);}.jcrop-holder {	margin: 0 auto;	position: absolute;	top: 0;	left: 0;	right: 0;	bottom: 0;	z-index: 290;}

This code sets the dimensions and styles for the cropping container and image, and also adjusts the styling of the Jcrop holder.

Conclusion

In this tutorial, you learned how to crop an image using the Jcrop JavaScript library and the Intervention Image library in Laravel. You also learned how to handle image uploads and retrieve image dimensions using PHP. By following the steps outlined in this tutorial, you can easily implement image cropping functionality in your Laravel applications.

Comments