Crop Image and Save into Database using PHP with Ajax

Today we learn how to Crop Image and Save into Database using PHP with Ajax

In this post, we learn how to Crop Image and Save into Database using PHP with Ajax.

In this blog post, you can learn Crop Image and Save into Database using PHP with Ajax and javascript and then after that cropped image stored into MySQL database in Base 64  format. In this application, we will some Bootstrap code for modal.

To store the image in the database rather than the public folder or asset folder is benefits are image has been load faster than image load from the folder. the second advantage to store the image in the database is not cached in the browser and many other advantages to storing the image in the database.

The many rich text box editor is also converting uploaded image into a base64 format and then store into database.

Now we have seen the all process of crop image and store into MySQL database step by step. first, we need to the select an image, then Croppie plugin has been initializing, and by using this plugin we can zoom the image, and as per our requirement, we can crop the image. 

First, create a database table to store image

CREATE TABLE `tbl_images` (
  `id` int(11) NOT NULL,
  `images` bigint NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Column name image where we store image storage type should be Bigint. Because of the size of the converted image in the base64 format length is too long.

Create an Index.php page

<html> 
  <head> 
    
<title>Crop Image and Save into Database using PHP with Ajax</title> 
 
<script
 src=//code.jquery.com/jquery-3.3.1.min.js
 integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
 crossorigin=anonymous></script>

 <link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin=anonymous>

<script src=//cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.js></script>

 <link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />

 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css" />

  </head> 
  <body> 
    <div >
     <br />
   <h3 align=center> Crop Image and Save into Database using PHP with Ajax</h3>
   <br />
   <br />
  <div >
   <div >Select Profile Image</div>
   <div align=center>
    <input type=file name=insert_image id="insert_image" accept="image/*" />
    <br />
    <div id="store_image"></div>
   </div>
   </div>
  </div>
  </body> 
</html>

<div id="insertimageModal" role="dialog">
 <div >
 <div >
   <div >
    <button type=button data-dismiss="modal">&times;</button>
    <h4 >Crop & Insert Image</h4>
   </div>
   <div >
    <div >
     <div >
      <div id="image_demo" ></div>
     </div>
     <div >
    <br />
    <br />
    <br/>
      <button >Crop & Insert Image</button>
     </div>
    </div>
   </div>
   <div >
    <button type=button 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
  }  
 });

 $('#insert_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]);
  $('#insertimageModal').modal('show');
 });

 $('.crop_image').click(function(event){
  $image_crop.croppie('result', {
   type: 'canvas',
   size: 'viewport'
  }).then(function(response){
   $.ajax({
    url:'insert.php',
    type:'POST',
    data:{"image":response},
    success:function(data){
     $('#insertimageModal').modal('hide');
     load_images();
     alert(data);
    }
   })
  });
 });

 load_images();

 function load_images()
 {
  $.ajax({
   url:"fetch_images.php",
   success:function(data)
   {
    $('#store_image').html(data);
   }
  })
 }

}); 
</script>

Create another file database_connection.php

Create a new database_connection.php file for connection with the database. In my case database name is cropImage and username is root and the password are blank.

<?php
$connect = new PDO("mysql:host=localhost;dbname=cropImage", "root", "");
?>

Create a file insert.php

Here we create a new file for data insert into the database. In this file, we receive an image and store it in the database in the base64 format.

<?php

//insert.php

if(isset($_POST["image"]))
{
 include('database_connection.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 tbl_images(images) VALUES ('".$image_file."')";

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

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

}

?>

fetch_images.php

After saving data(Image) into the database we need to display on the page to create a new file fetch_image.php

<?php

//fetch_images.php

include('database_connection.php');

$query = "SELECT * FROM tbl_images ORDER BY image_id DESC";

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

$output = '<div >';

if($statement->execute())
{
 $result = $statement->fetchAll();

 foreach($result as $row)
 {
 $output .= '
 <div >
  <img src=data:image/png;base64,'.base64_encode($row['images']).' />
 </div>
 ';
 }
}

$output .= '</div>';

echo $output;

?>

So here over our post for Crop Image and Save into Database using PHP with Ajax