Crop and Save Images using jQuery and PHP

In this tutorial, we will show you how to crop, resize images and store them in the database using jQuery Croppi, ajax with a preview in PHP.

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

Steps to crop, resize, store, and preview images using jQuery, 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.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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