Image Crop and Save into Database using PHP + jQuery + Ajax

To crop and upload image in PHP + MySQL database + jQuery croppie and ajax. in this tutorial, i am going to show you how to crop image before upload to database in PHP + MySQL + jQuery Croppie + Ajax. And as well as how to use ajax to send image file into server without refresh whole web page in PHP + MySQL.

Croppie is a powerful JavaScript library, it allows fast, subtle image cropping not only but also it comes with tons of features to adjust the image cropping.

Cropping is the process of removing the unnecessary areas from an image. Cropping is usually done to remove the needless areas of an image. It takes out the useless stuff from the picture and enhances its framing, and it even changes the aspect ratio.

Image Crop and Save Into Database using PHP + jQuery Croppie + Ajax

  • Step 1 – Start Apache Web Server
  • Step 2 – Create PHP Project
  • Step 3 – Create Table and Database Connection File
  • Step 4 – Create Crop and Upload Image Html Form
    • Create Image Upload Form
    • Integrate Croppie JS in HTML
    • Create Bootstrap Modal for Crop Image
    • Implement Ajax Code to Send Image into Server
  • Step 5 – Store Crop Image into Database
  • Step 6 – Test This PHP App

Step 1 – Start Apache Web Server

Now, you need to start your apache web server. And as well as start Apache and mysql web server. You can see in the image below how to start apache and mysql server:

start xampp apache mysql server
start xampp apache mysql server

Step 2 – Create PHP Project

In step 2, navigate to your xampp/htdocs/ directory. And inside xampp/htdocs/ directory, create one folder. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 3 – Create Table and Database Connection File

In step 3,, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;


CREATE TABLE `images` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`file` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;

Then create a php file that named mydb.php. Which is used to connect phpmyadmin mysql database to project folder(demo).

So, now create mydb.php file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $conn = mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>
Step 4 – Create Crop and Upload Image Html Form

In step 4, create a php file that named index.php. Which is used to display crop and image upload form and store image file database into MySQL database in PHP, So add the following code into it:

Create Image Upload Form

Create Image upload form and add into index.php file; as shown below:

<html>  
    <head>  
        <title>Crop and Save Image using jQuery ajax and PHP</title>  
  
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
    </head>  
    <body>  
    <div class="container mt-5">
     <div class="card">
      <div class="card-header">
        Crop and Save Image using jQuery ajax and PHP
      </div>
      <div class="card-body">
       <input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
       </div>
    </div>
    </div>
    </body>  
</html>

Integrate Croppie JS in HTML

Add the following lines jQuery croppie js library in html form:

Create Bootstrap Modal for Crop Image

Create bootstrap model for crop and upload into database and add into index.php file; as shown below:

<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
 <div class="modal-dialog modal-lg">
  <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-8 text-center">
            <div id="image_demo" style="width:350px; margin-top:30px"></div>
          </div>
          <div class="col-md-4" style="padding-top:30px;">
        <br />
        <br />
        <br/>
            <button class="btn btn-success crop_image">Save</button>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Implement Ajax Code to Send Image into Server

Implement jQuery ajax code for send file to server, so add into index.php file; as shown below:

<script>  
$(document).ready(function(){

 $image_crop = $('#image_demo').croppie({
    enableExif: true,
    viewport: {
      width:200,
      height:200,
      type:'square' //circle
    },
    boundary:{
      width:300,
      height:300
    }    
  });

  $('#before_crop_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]);

    $('#imageModel').modal('show');
  });

  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:'crop-image-store.php',
        type:'POST',
        data:{"image":response},
        success:function(data){
          $('#imageModel').modal('hide');
          alert('Crop image has been uploaded');
        }
      })
    });
  });

});  
</script>

Complete source code of index.php file; as below:

<html>  
    <head>  
        <title>Crop and Save Image using jQuery ajax and PHP</title>  
  
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
    </head>  
    <body>  
    <div class="container mt-5">
     <div class="card">
      <div class="card-header">
        Crop and Save Image using jQuery ajax and PHP
      </div>
      <div class="card-body">
       <input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
       </div>
    </div>
    </div>
    </body>  
</html>

<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
 <div class="modal-dialog modal-lg">
  <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-8 text-center">
            <div id="image_demo" style="width:350px; margin-top:30px"></div>
          </div>
          <div class="col-md-4" style="padding-top:30px;">
        <br />
        <br />
        <br/>
            <button class="btn btn-success crop_image">Save</button>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>  
$(document).ready(function(){

 $image_crop = $('#image_demo').croppie({
    enableExif: true,
    viewport: {
      width:200,
      height:200,
      type:'square' //circle
    },
    boundary:{
      width:300,
      height:300
    }    
  });

  $('#before_crop_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]);

    $('#imageModel').modal('show');
  });

  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:'crop-image-store.php',
        type:'POST',
        data:{"image":response},
        success:function(data){
          $('#imageModel').modal('hide');
          alert('Crop image has been uploaded');
        }
      })
    });
  });

});  
</script>

Step 5 – Store Crop Image into DB

In step 5, create one file that named upload.php file. This php file code will insert/store image file data into mysql database and directory.

Note that, If the image file upload is successfully inserted / stored into database, it will display success message. Otherwise if there is any error, it will display error message.

So, add the below code into your insert.php file:

<?php

//save crop image in php

if(isset($_POST["image"]))
{
 include('db.php');

 $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);

 $image_file = addslashes(file_get_contents($imageName));

 $query = "INSERT INTO images(file) VALUES ('".$image_file."')";

 $statement = $connect->prepare($query);

 if($statement->execute())
 {
  echo 'Image save into database';
  unlink($imageName);
 }

}

?>

Step 6 – TestThis PHP App

Finally, you need to open your browser and type http://localhost/demo/ this run project on local machine.

Conclusion

To crop and upload image in PHP + MySQL database + jQuery croppie and ajax. Through this tutorial, you have learned how to crop image before upload to database in PHP + MySQL + jQuery Croppie + Ajax. And as well as how to use ajax to send image file into server without refresh whole web page in PHP + MySQL.

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *