Crop and Save Image Using jQuery Croppie and PHP

Crop and Save Image Using jQuery Croppie and PHP

Ajax image upload and crop with jquery croppie and PHP. Here, we will show you how to crop, resize image size and store into the database using jQuery croppie with ajax in PHP.

Here, we will use jQuery croppie libaray to crop and resize images before upload to database with ajax in PHP.

This tutorial will guide you step by step to upload crop and resize using jquery ajax in PHP.

Image Crop and Save Into Database using PHP With jQuery Croppie, Ajax

Just follow the below given easy steps to crop image, resize and store image into database in php using jQuery croppie and ajax:

  • Step 1: Create Image Table For Store Crop and Resize Image
  • Step 2: Create DB Connection PHP File
  • Step 3: Create Html Form To Display Crop And Resize Image
  • Step 4: Store Crop Image and Resize Image Using Ajax

Step 1: Create Image Table For Store Crop and Resize Image

First of all, open your database and run the following sql queries to create country, state and city table into the database:

Run this following sql query to create crop_image table into your database:

--
-- Table structure for table `crop_images`
--

CREATE TABLE `crop_images` (
  `id` int(11) NOT NULL,
  `title` longblob NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `crop_images`
--
ALTER TABLE `crop_images`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `crop_images`
--
ALTER TABLE `crop_images`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Step 2: Create DB Connection PHP File

In this step, create a file name db.php and update the following code into db.php file:

<?php
	$servername='localhost';
	$username='root';
	$password='';
	$dbname = "my_db";
	$conn=mysqli_connect($servername,$username,$password,"$dbname");
	  if(!$conn){
		  die('Could not Connect MySql Server:' .mysql_error());
		}
?>

Note that, This code is used to create a MySQL database connection in PHP project.

Step 3: Create Html Form To Display Crop And Resize Image

In this step, create an index.php file and update the below PHP and HTML code into index.php file.

Note that, This HTML code shows the crop image form and bootstrap model. Because you can crop image and resize image on bootstrap model. After that store into database using jquery ajax.

Now, update the following html form into index.php file:

<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.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 4: Store Crop Image and Resize Image Using Ajax

In this step, create an again new PHP file named crop-image-store.php. This PHP code will store crop and resize image into database table.

To update the following php and html code into crop-image-store.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 crop_images(title) VALUES ('".$image_file."')";

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

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

}

?>

Conclusion

Crop, resize and save image using jquery in PHP with ajax tutorial, you have learned how to crop and resize image size using jquery croppie. And store crop image into database table in PHP.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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