Laravel is a powerful PHP framework for web development that offers an array of features and functionalities that make web development more efficient and effective. One such feature is the ability to crop images before uploading using Cropper JS. Cropper JS is a lightweight and easy-to-use JavaScript library that provides an intuitive interface for cropping images.
In this article, we will guide you through the process of implementing Cropper JS in Laravel and cropping images before uploading.
Step 1: Install Laravel
Before we begin, ensure that you have Laravel installed on your system. You can install Laravel by following the official documentation at https://laravel.com/docs/8.x/installation.
Read Also : Crop and Upload image in laravel using jcrop js
Step 2: Install Cropper JS
Once Laravel is installed, we can proceed to install Cropper JS. To install Cropper JS, open the terminal and navigate to the root directory of your Laravel project. Run the following command to install Cropper JS via npm.
npm install cropperjs
or use Cropper JS CDN
If you want to use a CDN to serve the Cropper JS library instead of downloading it locally, you can replace the <script>
tag that includes the library in your image-upload.blade.php
file with the following code:
<script src="https://cdn.jsdelivr.net/npm/cropperjs@2.3.4/dist/cropper.min.js"></script>
This will load the Cropper JS library from the jsDelivr CDN instead of from a local file.
You can also use a CDN to serve the jQuery library if you are not already using it on your website. To do this, replace the <script>
tag that includes the jQuery library in your image-upload.blade.php
file with the following code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
This will load the jQuery library from the jQuery CDN.
Step 3: Include Cropper JS in Your Project
After installing Cropper JS, we need to include it in our Laravel project. Open the resources/js/app.js
file and add the following code at the bottom of the file.
require('cropperjs');
Next, run the following command to compile the JavaScript files.
npm run dev
Step 4: Create a Form for Image Upload
To enable image cropping before uploading, we need to create a form that allows users to select an image and preview it. To create the form, open the resources/views
directory and create a new file called image-upload.blade.php
. Add the following code to the file.
<form action="{{ route('image.upload') }}" method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="image" id="image" class="form-control"> <div class="preview"></div> <button type="submit" class="btn btn-primary">Upload Image</button></form>
In the code above, we have created a form with an input field that allows users to select an image. We have also added a preview section to the form where the selected image will be displayed. Finally, we have added a submit button to the form.
Step 5: Implement Cropper JS
Now that we have created the form, we need to implement Cropper JS to enable image cropping. To do this, add the following code to the image-upload.blade.php
file.
<script> $(document).ready(function() { $('#image').on('change', function() { var input = $(this)[0]; if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('.preview').html('<img id="image-preview" src="' + e.target.result + '">'); $('#image-preview').cropper({ aspectRatio: 1, viewMode: 1, crop: function(e) { // Output the result data for cropping image. console.log(e.detail.x); console.log(e.detail.y); console.log(e.detail.width); console.log(e.detail.height); console.log(e.detail.rotate); console.log(e.detail.scaleX); console.log(e.detail.scaleY); } }); }; reader.readAsDataURL(input.files[0]); } }); });</script>
In the code above, we have added an event listener to the image
input field. When an image is selected, Cropper JS is initialized and the selected image is displayed in the preview section. We have also set the aspectRatio
to 1 to maintain a square aspect ratio for the cropped image.
In addition, we have set the viewMode
to 1 to enable the user to crop the image within the preview section. Finally, we have added a crop
event listener that outputs the cropping data for the image.
Step 6: Crop the Image
Now that we have implemented Cropper JS, we can crop the image before uploading it to the server. To do this, we need to modify the image-upload.blade.php
file to include the cropping data in the form data before submitting the form.
<script> $(document).ready(function() { $('#image').on('change', function() { var input = $(this)[0]; if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('.preview').html('<img id="image-preview" src="' + e.target.result + '">'); $('#image-preview').cropper({ aspectRatio: 1, viewMode: 1, crop: function(e) { $('#image').attr('data-x', e.detail.x); $('#image').attr('data-y', e.detail.y); $('#image').attr('data-width', e.detail.width); $('#image').attr('data-height', e.detail.height); $('#image').attr('data-rotate', e.detail.rotate); $('#image').attr('data-scale-x', e.detail.scaleX); $('#image').attr('data-scale-y', e.detail.scaleY); } }); }; reader.readAsDataURL(input.files[0]); } }); $('form').submit(function(e) { e.preventDefault(); var formData = new FormData($(this)[0]); formData.append('x', $('#image').data('x')); formData.append('y', $('#image').data('y')); formData.append('width', $('#image').data('width')); formData.append('height', $('#image').data('height')); formData.append('rotate', $('#image').data('rotate')); formData.append('scaleX', $('#image').data('scale-x')); formData.append('scaleY', $('#image').data('scale-y')); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: formData, processData: false, contentType: false, success: function(response) { console.log(response); } }); }); });</script>
In the code above, we have added data attributes to the image
input field to store the cropping data. When the form is submitted, we append the cropping data to the form data and send it to the server using an AJAX request.
Step 7: Process the Image on the Server
Finally, we need to process the image on the server using Laravel. To do this, we need to create a route and a controller method to handle the image upload and cropping.
// routes/web.phpRoute::post('/image/upload', [ImageController::class, 'upload'])->name('image.upload');
//app/Http/Controllers/ImageController.phpuse Illuminate\Http\Request;use Intervention\Image\Facades\Image;class ImageController extends Controller{ public function upload(Request $request) { $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image = Image::make($image); $image->crop( $request->input('width'), $request->input('height'), $request->input('x'), $request->input('y') ); $image->save(public_path('uploads/' . $filename)); return response()->json([ 'success' => true, 'file' => [ 'url' => asset('uploads/' . $filename), ], ]);}}
In the code above, we first retrieve the uploaded image file from the request and generate a unique filename for it. We then use the Intervention Image package to open the image and crop it using the cropping data sent from the client. Finally, we save the cropped image to the server and return a JSON response containing the URL of the cropped image file.
Conclusion
In this tutorial, we have demonstrated how to use Cropper JS and Laravel to crop an image before uploading it to the server. By using Cropper JS, we can provide an intuitive user interface for image cropping, and by using Laravel, we can easily process the cropped image on the server. With these tools, we can create powerful image upload and cropping functionality in our web applications.
Comments
Post a Comment