Welcome folks I am back with another blog post. In this post we will be Doing Image Crop and Upload using jQuery with PHP and AJAX. Image Crop is the most important part in every modern web application. In this post we will be implementing this feature in the following steps.
Make a new index.html file and copy paste the below code. In this code we have just a Image upload button.
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 |
<!DOCTYPE html> <html> <head> <title>Image Crop</title> <link rel="stylesheet" href="croppie.css"/> </head> <body> <body> <div class="container"> <br> <h3 align="center">Image Crop and Upload using Jquery with Php and Ajax</h3> <br> <br> <p style="text-align:center;">Select Profile Image</p> <input type="file" name="upload_image" id="upload_image" accept="image/*"> <div id="uploadimage"> </div> <button class="crop_image">Crop and Upload Image</button> <div id="uploaded_image"></div> </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="croppie.min.js"></script> <script src="script.js"></script> </html> |
For this we are using the croppie library for cropping images so download this library from here
Make a new script.js file for the javascript
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 |
$(document).ready(function(){ $(".crop_image").hide(); $image_crop = $('#uploadimage').croppie({ enableExif: true, viewport: { width:200, height:200, type:'square' //circle }, boundary:{ width:300, height:300 } }); $('#upload_image').on('change', function(){ var reader = new FileReader(); reader.onload = function (event) { $image_crop.croppie('bind', { url: event.target.result }).then(function(){ console.log('jQuery bind complete'); }); } reader.readAsDataURL(this.files[0]); $(".crop_image").show(); }); $('.crop_image').click(function(event){ $image_crop.croppie('result', { type: 'canvas', size: 'viewport' }).then(function(response){ $.ajax({ url:"upload.php", type: "POST", data:{"image": response}, success:function(data) { $('#uploaded_image').html(data); $('.crop_image').hide(); } }); }) }); }); |
Make a new upload.php file. This php script will actually take the cropped image and upload it to the server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php //upload.php if(isset($_POST["image"])) { $data = $_POST["image"]; $image_array_1 = explode(";", $data); $image_array_2 = explode(",", $image_array_1[1]); $data = base64_decode($image_array_2[1]); $imageName = time() . '.png'; file_put_contents($imageName, $data); echo '<img src="'.$imageName.'" class="img-thumbnail" />'; } ?> |