Crop and Save Image using jQuery Coppie in Codeigniter 4

Crop and Save Image using jQuery Coppie in Codeigniter 4

Codeigniter – crop image before upload using jQuery croppie with ajax. Here, we will show you how to crop and resize image before upload/save to database in codeigniter using jQuery croppie with ajax.

In this tutorial, we will teach you how to use jQuery for image upload with ajax in Codeigniter 4 project. Also, how to show a preview of crop and resize image before save into the database and folder using Ajax. And without refreshing and reloading the whole web page of your CodeIgniter 4 application.

Codeigniter Crop Image Upload using jQuery Croppie and Ajax

Use the below given steps to crop, resize and save image using jquery with ajax in php codeigniter:

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Start Development server

Step 1: Download Codeigniter Project

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

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 text editor.

Set Base URL like this

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 name demo, so open PHPMyAdmin and create the database with the name demo. After successfully create a database, you 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 database.php file in text editor. After opening the file in a text editor, 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:

  • Index() – This is used to display crop image before upload form.
  • Store() – This is used to validate form file/image on server-side and store crop image into MySQL database and folder.
<?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</title>  
  
    </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>

Add this jQuery croppie plugin libaray into crop-image-upload-form.php file:

<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" />

Then, add this below code into crop-image-upload-form.php file to crop image before upload on boostrap model in codeigniter:

$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');
  });

Also, add this below ajax code in crop-image-upload-form.php for upload crop image into controller file in codeigniter 4 projects:

$('.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');
        }
      })
    });
  });

Full code of crop-image-upload-form.php file as given below:

<html>  
<head>  
<title>jQuery Croppie Image Upload Crop Codeigniter 4</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: 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

Conclusion

Codeigniter 4 upload crop and resize image using jQuery croppie. Here, You have learned how to crop and resize image before upload in CodeIgniter 4 projects using jQuery croppie with ajax with preview.

Recommende CodeIgniter 4 Tutorial

  1. Install / Download Codeigniter 4 By Manual, Composer, Git
  2. Codeigniter 4 Remove Public and Index.php From URL
  3. Codeigniter 4 Application Folder / Directory Structure
  4. Create Controller, Model, View Example Codeigniter 4

If you have any questions or thoughts to share, use the comment form below to reach us.

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, Vue JS, Angular JS, React Js, WordPress, 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 *