Codeigniter 4 Image Crop and Save using Croppie Example

Crop image before upload in codeigniter 4. In this tutorial, i will guide you step by step how to crop and save image using jquery croppie in codeigniter 4 with bootstrap modal.

Whenever you need to crop the image before uploading and store the cropped image in database using Ajax and bootstrap modal. So for in this example, I will use jquery croppie and ajax to crop image with croppie and upload image using ajax and bootstrap modal in codeigniter 4 app.

Croppie is a powerful JavaScript library, it allows fast, subtle image cropping not only but also it comes with tons of features to adjust the image cropping.

For the Codeigniter 4 crop image before upload example , I’ll create a simple image upload form with bootstrap modal and add jQuery croppie functionality to crop image before upload. And open the image on the Bootstrap modal and crop it. As well as, store the cropped image in the database end directory.

Crop and Save Image using jQuery Croppie in Codeigniter 4

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

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

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE DATABASE demo;

CREATE TABLE images (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    type varchar(255) NOT NULL COMMENT 'file type',
    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

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
	];

Step 5 – Create Controller

Create CropImageController.php file. So, visit app/Controllers directory and create CropImageController.php.Then add the following code into it:

<?php namespace App\Controllers;

use CodeIgniter\Controller;

class CropImageUpload extends Controller
{
    public function index()
    {    
         return view('crop_image_form');
    }

    public function store()
    {  
	       helper(['form', 'url']);
        
	       $db    = \Config\Database::connect();
         $builder = $db->table('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);

    }
}

The index() function renders the contact form template into the view.

The save() method handles the form of validation and contains various variables. And store image into db and directory.

Step 6 – Create Views

Create crop_image_form.php view file, so visit application/views/ directory and create crop_image_form.php file. Then add the following HTML into crop_image_form.php file:

<html>  
    <head>  
        <title>Codeigniter 4 Crop Image Before Uplaod using jQuery Croppie - Laratutorials.com</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/[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">
        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 & 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 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->setDefaultController('CropImageController');
$routes->get('/', 'CropImageController::index');
$routes->post('save', 'CropImageController::store');

Note that, the routes will be displaying the image upload form and bootstrap modal for cropping image and submitting the data in the database on successful form submission.

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

CodeIgniter 4 crop image before upload tutorial. In this example,you have learned how to crop and save image using jquery in codeigniter 4 apps. And also will learned how to store crope image into db and directory..

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. CodeIgniter 4 Server Side DataTable Example
  16. Create Rest Api In Codeigniter 4 App

Leave a Comment