Sunday, 25 November 2018

Image Crop and Save into Database using PHP with Ajax



Do you know How to Store or Insert Crop image into Mysql database with PHP script. If you looking such type of tutorial, then you have come on best post. In this post you can learn How to crop an Image by using Croppie javascript plugin and then after that croped image has been inserted into mysql database by using PHP script with Ajax and Bootstrap modal. In one of our post like Image Crop and Upload into folder using javascript plugin with PHP and Ajax, in that post you can find before upload of image, it has been crop by using javascript Croppie plugin, and after crop of image it will store into folder using Ajax with PHP.

Why we have to store image into Mysql database in place of store image info folder, there is one benefit is that if we have store image into database then it has been load faster than image load from folder. There is one another benifit is that image which are store in database is not cache in browser, while image load from folder has been easily cache in browser. There are some more other benifit for storing image into database. So, Here we have do two operation like first we have crop image by using jQuery plugin, and after crop image has been inserted into mysql database.

Now we have seen whole process of crop image and store into mysql database. When first we have select image, then Croppie plugin has been initialize, and by using this plugin we can zoom image, and as per our requirement we can crop image. Once image has been crop then this plugin has convert crop image into binary string format. By using base64_decode() function we decode binary string into image, and by using file_put_contents() we have create under local folder. Once Image has been created and under store under folder, we ahve convert into binary string format by using file_get_contents() and addslashes() function. Then after run insert query and store into database. Once crop image has been store into database by using unlink() function, it will be remove from local folder also. This is whole process of Image crop and Save into Mysql database by using javascript croppie plugin with PHP and Ajax. Below you can find complete source code of this tutorial.






Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_images`
--

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

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_images`
--
ALTER TABLE `tbl_images`
  ADD PRIMARY KEY (`image_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_images`
--
ALTER TABLE `tbl_images`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;


index.php



<html>  
    <head>  
        <title>Image Crop and Save into Database using PHP with Ajax</title>  
  
  <script src="jquery.min.js"></script>  
  <script src="bootstrap.min.js"></script>
  <script src="croppie.js"></script>
  <link rel="stylesheet" href="bootstrap.min.css" />
  <link rel="stylesheet" href="croppie.css" />
    </head>  
    <body>  
        <div class="container">
          <br />
      <h3 align="center">Image Crop and Save into Database using PHP with Ajax</h3>
      <br />
      <br />
   <div class="panel panel-default">
      <div class="panel-heading">Select Profile Image</div>
      <div class="panel-body" 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" class="modal" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Crop & Insert Image</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">Crop & Insert Image</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
    }    
  });

  $('#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>





database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


insert.php



<?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



<?php

//fetch_images.php

include('database_connection.php');

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

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

$output = '<div class="row">';

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

 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-2" style="margin-bottom:16px;">
   <img src="data:image/png;base64,'.base64_encode($row['images']).'" class="img-thumbnail" />
  </div>
  ';
 }
}

$output .= '</div>';

echo $output;

?>

4 comments: