Today, we are going to cover PHP crop image before upload tutorial to see how to crop and resize image on the fly in your project.
It is very handy since you dont have to every time resize and crop the image in any way you want after implementing this technique in one of your project.
We are going to use cropper js library for it. So if you want to learn more about it check its documentation and try to configure and implement if in your project by yourself. If you have problem regarding it then, you can follow along my tutorial.
Recently I have also wrote a tutorial on crop an image with jcrop library in php. If you want to check that out, you might find that easy to integrate than cropper JS.
Let’s get started.
What are we going to do ?
- Create basic layout structure with select button for images
- Import jQuery, bootstrap, cropper js libraries in your project.
- Use PHP image crop library and integrate it.
PHP Crop Image Before Upload
Let’s take it step by step so that it would be very easier to understand on how to implement this in your project.
Create Basic Layout Structure
First create a basic layout structure for your project. So what will be needing is a input which will upload an image and we will see how we will use cropper JS which in PHP image crop library to crop image and send it to database.
So here is my basic structure of the page in html code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<div class="container mt-5"> <div class="row"> <div class="col-md-7 m-auto"> <h1 class="h3 float-start">Upload & Crop Image Using Cropper JS</h1> <small class="float-end mt-3"><a href="https://blog.shashankbhattarai.com.np/cropper-js-image-cropper">CodeInHouse Tutorials</a></small> <div class="input-group mb-3"> <input type="file" class="form-control" id="cropped-image" accept="image/png, image/gif, image/jpeg"> <input type="hidden" name="cropped_image" id="cropped_image_text"> </div> <div class="cropped-image d-block"> <img src="" id="cropped-image-preview" width="200px" style="display: none;" alt="cropped_image_preview"/> </div> </div> </div> </div> <div class="modal" tabindex="-1" id="crop-modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Crop Image</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body text-center"> <div class="position-relative"> <img src="" id="image_to_crop" alt="image_to_crop"/> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" id="dont-crop">Don't crop</button> <button type="button" id="crop-image" class="btn btn-primary">Crop</button> </div> </div> </div> </div> |
Import jQuery, Bootstrap, Cropper JS Libraries
Secondly, you have to import some of the libraries. I have used the bootstrap framework so that you have to import bootstrap also in order to get a nice looking UI. Next is jQuery and cropper js, cropper js is the jQuery library so, we have to import in order to use it.
Copy and paste these libraries below :-
1 2 3 4 5 6 |
<!-- stylesheet --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css"> <!-- script --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js"></script> |
Use PHP Image Crop Library and Integrate (CROPPER JS)
Finally, its time to integrate php image crop library and crop image while you select and export it and save it to database. However we are not going to save it into the database but you will get the value that you need to save. You just have to make the ajax call and save it to database.
So, let’s divide into step by step on what are we going to do. I am writing all the steps inside the code itself so before just copying and pasting the code in your project and using.
- When user select’s an image and open modal to allow user to crop the image.
- User choose both crop and not to crop the image. So if user crops an image save the cropped image and return the name of image as an input and save it. Similarly, if user choose not to crop return image name as it is and copy it to folder and you can save the name into the database.
Now, let’s take a look at the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
$(document).ready(() => { const cropModal = $('#crop-modal').modal({backdrop: 'static', keyboard: false}); const modalImgElement = document.querySelector('#image_to_crop'); let cropper = null; // When Choose files button is clicked and image is selected $("#cropped-image").change(($event) => { const files = $event.target.files; if (files && files.length > 0) { let fileReader = new FileReader(); fileReader.onload = () => { modalImgElement.src = fileReader.result; cropModal.modal('show'); } fileReader.readAsDataURL(files[0]); } }); // common function library const crop_image = () => { let canvas = cropper.getCroppedCanvas(); canvas.toBlob((blob) => { URL.createObjectURL(blob); const fileReader = new FileReader(); fileReader.readAsDataURL(blob); fileReader.onloadend = () => { const base64ImageData = fileReader.result; const ajaxParams = { url: 'crop.php', method: 'POST', data: {imageFile: base64ImageData}, success: (response) => { cropModal.modal('hide') $("#cropped_image_text").val(response); $("#cropped-image-preview").attr('src', 'img/' + response).show(); }, error: (error) => alert(error) } $.ajax(ajaxParams); } }); } let crop_on_modal_dissmiss = () => { let container_data = cropper.getContainerData(); cropper.setCropBoxData({height: container_data.height, width: container_data.width}); crop_image(); } // when modal popup's initialize CropperJs const options = {initialAspectRatio: 16 / 9, viewMode: 3, zoomable: false} cropModal.on('shown.bs.modal', cropModal, () => cropper = new Cropper(modalImgElement, options)) .on('hidden.bs.modal', () => (cropper.destroy(), cropper = null)); // When the crop button is clicked crop image and set it to your preview and then close modal $("#crop-image").on('click', () => crop_image()); // If user chooses not to crop and presses dont crop or press close or cancel $("#dont-crop").on('click', () => crop_on_modal_dissmiss()); }); |
So, that is everything with PHP crop image and save using jQuery and PHP using Cropper JS library. If you had any problem with these codes you can comment below.
Leave a Reply