Crop And Save Image Using JQuery Coppie In Codeigniter


Today I will show the Crop image before upload using jQuery croppie with ajax. I will show crop and resize image before uploading to database in Codeigniter. 

In this tutorial, we will learn crop image in PHP. this tutorial uses jQuery for image upload with ajax in Codeigniter 4 project. image show a preview of crop and resizes image before save in database using Ajax. And without refreshing and reloading web page of your CodeIgniter project. we will learn crop image in Codeigniter.

[Crop And Save] Image Using JQuery Coppie In Codeigniter- Step By Step
Step 1: Download Codeigniter Project

In this step, we will download the latest version of Codeigniter 4, Go to this link Download Codeigniter 4 fresh new setup and unzip the setup in your local system. And change the download folder name “your folder name”.

Step 2: Basic Configurations

Next, we will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on the text editor.

public $baseURL = 'http://localhost:8080';


To

public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table

In this step, we need to create a database. can use the below SQL query for creating a crop_images table in your database.

CREATE TABLE crop_images (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    title varchar(100) NOT NULL COMMENT 'Title',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;
Step 4: Setup Database Credentials

In this step, we need to connect our project to the database. we need to go app/Config/Database.php and open the database.php. We need to set up database credentials in this file like below.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];
Step 5: Create Controller

Now Go to app/Controllers and create a controller name CropImageUpload.php. In this controller, we will create some method/function:

<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
 
class CropImageUpload extends Controller
{
    public function index()
    {    
         return view('crop-image-upload-form');
    }
 
    public function store()
    {  
           helper(['form', 'url']);
         
           $db    = \Config\Database::connect();
         $builder = $db->table('crop_images');
 
 
         $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));
 
         $save = $builder->insert(['title' =>  $image_file]);
 
         $response = [
          'success' => true,
          'data' => $save,
          'msg' => "Crop Image has been uploaded successfully in codeigniter"
         ];
     
 
       return $this->response->setJSON($response);
 
    }
}
Step 6: Create Views

Now we need to create crop-image-upload-form.php, go to application/views/ folder, and create crop-image-upload-form.php file. and update the following HTML into your files:

<html>
   <head>
      <title>jQuery Croppie Image Upload Crop Codeigniter 4 PHP Coding Stuff</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://code.jquery.com/jquery-3.5.1.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/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">
               jQuery Crop and Resize Image Before Upload in PHP Codeigniter 4  
            </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 &amp; 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: "<?php echo base_url(); ?>public/index.php/CropImageUpload/store",
                type: 'POST',
                data: {
                    "image": response
                },
                success: function(data) {
                    $('#imageModel').modal('hide');
                    alert('Crop image has been uploaded');
                }
            })
        });
    });
});
</script>
Step 7: Start Development Server

For start development server, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/crop-image-upload

[Crop And Save] Image Using JQuery Coppie In Codeigniter- Step By Step

I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close