Cropping an Image before Saving using JS, jQuery, and PHP Tutorial

Introduction

In this tutorial, I will show you How to Crop an Image before Saving it using JS, jQuery, and JS Library. We can achieve this kind of feature for our web application by using Croppie Library. The tutorial aims to provide the student and new programmers a reference to learn with to enhance and develop their programming skills using JavaScript and PHP Language. Here, snippets and sample source codes are provided.

How to Crop Image before Saving it

There are a lot of options to Crop an Image in web development. This feature is usually created using JavaScript to allow the end-users to crop the image on the client side. We can create this kind of feature by using DOM Manipulation, event listeners, and some other method or object that are available in JavaScript. Writing code for this might be time-consuming and not easy, especially for beginners. But, with the help of Croppie Library, we can achieve this kind of feature without hassle.

What is Croppie Library?

Croppie Library is a JavaScript Library that was developed by Foliotek. This library comes with JavaScript and CSS files. It was mainly created to crop an image using JavaScript. You can download this library at https://github.com/Foliotek/Croppie/releases.

How to use Croppie Library?

Here are some snippets of using the Croppie Library to crop an Image before saving it in your web server. The said library comes with multiple options and methods that you can use.

Here's a basic example of using the Library

  1. var $croppie = new Croppie($('#croppie-element')[0], {
  2. boundary: { width: 400, height: 400 },
  3. viewport: {
  4. height: 300,
  5. width: 300,
  6. type:'square'
  7. },
  8. })

The script above is only initializing the Cropping Feature to the specific element in your web page or HTML page. It will create a container and field where you can edit or crop your chosen image.

To bind an Image to the library. You can use the following snippet.

  1. $croppie.bind({
  2. url: "sample_img.png",
  3. });

The script above will bind your chosen image to the cropper element where you can adjust the image and select the part of the image to crop.

After you finish cropping the image, you can get the cropped image using the result method of the library. You can choose the format of the image (PNG, JPEG, WEBP) and select the type of result you want ('canvas', 'html', 'blob', or, 'rawcanvas'). Here's the following example to do it.

  1. $croppie.result('blob').then(function(blob) {
  2. // do something here and use blob variable to get the cropped image result
  3. });

Example

Here's a sample application that demonstrates how to crop images before saving them using Croppie Library, jQuery, Ajax, and PHP. This application allows users to upload and crop images. The browsed or chosen image can be also rotated clockwise or counterclockwise. Users can also resize the cropping container.

Interface

index.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Crop Image using Croppie JS</title>
  7.  
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="./croppie/croppie.css">
  10. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  11. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  12. <script src="./croppie/croppie.js" ></script>
  13. html, body{
  14. min-height:100%;
  15. width:100%;
  16. }
  17. .img-holder {
  18. width: calc(100%);
  19. height: 30vh;
  20. background: black;
  21. }
  22. .img-holder img{
  23. object-position:
  24. }
  25. .img-holder img {
  26. width: calc(100%);
  27. height: calc(100%);
  28. object-fit: scale-down;
  29. object-position: center center;
  30. }
  31. </style>
  32. </head>
  33. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  34. <div class="container">
  35. <a class="navbar-brand" href="./">Crop Image using Croppie JS</a>
  36. <div>
  37. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  38. </div>
  39. </div>
  40. </nav>
  41. <div class="container-fluid px-5 my-3">
  42. <div class="clearfix my-3"></div>
  43. <div class="row">
  44. <div class="col-lg-6">
  45. <div class="card rounded-0">
  46. <div class="card-body rounded-0">
  47. <form action="upload.php" method="POST" enctype="multipart/form-data">
  48. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  49. <div class="mb-3">
  50. <label for="upload" class="form-label">Upload File</label>
  51. <input class="form-control" type="file" name="upload" accept="image/jpeg, image/png" id="upload">
  52. </div>
  53. </div>
  54. </form>
  55. <div id="croppie-editor" class="d-none">
  56. <div id="croppie-field"></div>
  57. <div class="mx-0 text-center">
  58. <button class="btn btn-sm btn-light border border-dark rounded-0" id="rotate-left" type="button">Rotate Left</button>
  59. <button class="btn btn-sm btn-light border border-dark rounded-0" id="rotate-right" type="button">Rotate Right</button>
  60. <button class="btn btn-sm btn-primary rounded-0" id="upload-btn" type="button">Upload</button>
  61. </div>
  62. </div>
  63. </div>
  64. </div>
  65. </div>
  66. <div class="col-lg-6">
  67. <div class="card round-0 rounded-0">
  68. <div class="card-body rounded-0">
  69. <div class="container-fluid">
  70. <div class="d-flex flex-wrap">
  71. <?php
  72. $dir = "uploads/";
  73. if(is_dir($dir)):
  74. $scandir = scandir($dir);
  75. foreach($scandir as $img):
  76. if(in_array($img, ['.', '..']))
  77. continue;
  78. ?>
  79. <div class="col-lg-4 col-md-6 col-sm-12 p-1">
  80. <div class="position-relative img-holder">
  81. <img src="<?= $dir.$img ?>" alt="">
  82. </div>
  83. </div>
  84. <?php endforeach; ?>
  85. <?php endif; ?>
  86. </div>
  87. </div>
  88. </div>
  89. </div>
  90. </div>
  91. </div>
  92. </div>
  93. <script src="app.js" ></script>
  94.  
  95. </body>
  96. </html>

JavaScript

app.js

  1. var $croppie = new Croppie($('#croppie-field')[0], {
  2. enableExif: true,
  3. enableResize:true,
  4. enableZoom:true,
  5. boundary: { width: 400, height: 400 },
  6. viewport: {
  7. height: 300,
  8. width: 300
  9. },
  10. enableOrientation: true
  11. })
  12. $(document).ready(function(){
  13. var img_name;
  14. // console.log($croppie)
  15. $('#upload').on('change', function(e){
  16. var reader = new FileReader();
  17. img_name = e.target.files[0].name;
  18. reader.onload = function (e) {
  19. $croppie.bind({
  20. url: e.target.result
  21. });
  22. $('#croppie-editor').removeClass('d-none')
  23. }
  24. reader.readAsDataURL(this.files[0]);
  25. })
  26.  
  27.  
  28. $('#rotate-left').click(function(){
  29. $croppie.rotate(90);
  30. })
  31. $('#rotate-right').click(function(){
  32. $croppie.rotate(-90);
  33.  
  34. })
  35. $('#upload-btn').click(function(){
  36. $croppie.result({
  37. type:'base64',
  38. format: 'png'
  39. }).then((imgBase64)=>{
  40. $.ajax({
  41. url:'save_image.php',
  42. method:'POST',
  43. data: { 'img' : imgBase64, 'fname' : img_name },
  44. dataType: 'json',
  45. error: err => {
  46. console.error(err)
  47. },
  48. success: function(response){
  49. if(response.status == 'success'){
  50. alert("Cropped Image has been saved successfully.")
  51. location.reload()
  52. }else{
  53. console.error(response)
  54. }
  55. }
  56. })
  57. })
  58. })
  59. })

Saving the Cropped Image

save_image.php

  1. <?php
  2.  
  3. extract($_POST);
  4. $dir = "uploads/";
  5. if(!is_dir($dir))
  6. mkdir($dir);
  7. $img = str_replace('data:image/png;base64,', '', $img);
  8. $img = str_replace(' ', '+', $img);
  9. $img = base64_decode($img);
  10. $save = file_put_contents($dir.$fname, $img);
  11. if($save){
  12. $resp['status'] = 'success';
  13. }else{
  14. $resp['status'] = 'failed';
  15.  
  16. }
  17. echo json_encode($resp);

Snapshot

Here's the snapshot of the result of the source code I provided above.

Crop Image using Croppie Library and PHP

I also provided the full source code zip file of the sample application on this website. You can download it by clicking the download button below this article. Leave a comment below with any questions you might want to ask regarding this tutorial.

That's it! I hope this Cropping Images before Saving Tutorial will help you with what you are looking for and that you'll find this useful for your current future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment