Codeigniter 4 Image Crop and Resize Before Save using jQuery Croppie Tutorial

In this tutorial, we will learn how to crop and resize an image before saving it in Codeigniter 4 using jQuery Croppie. Croppie is an easy to use javascript image cropper. It is very easy to use and provides a great user experience.

We will use jQuery Croppie to crop and resize an image before saving it in Codeigniter 4. We will also use the jQuery AJAX library to send the cropped image data to the server.

We will create a simple form with an image upload field. When the user selects an image, we will display the image in a Croppie instance. The user can then crop and resize the image before submitting the form.

We will then use the jQuery AJAX library to send the cropped image data to the server. On the server side, we will use the Codeigniter 4 Image Library to save the cropped image.

So let’s get started.

Step 1: Create a Codeigniter 4 Project

First, we need to create a Codeigniter 4 project. If you don’t already have one, you can create one using the following command:

composer create-project codeigniter4/appstarter

Step 2: Install jQuery and jQuery Croppie

Next, we need to install jQuery and jQuery Croppie. We can do this by downloading the latest version of jQuery and jQuery Croppie from their respective websites.

Once downloaded, we need to include the jQuery and jQuery Croppie files in our project. We can do this by adding the following code to the head section of our project’s main layout file:

Step 3: Create a Form

Next, we need to create a form with an image upload field. We can do this by adding the following code to our project’s main layout file:

Step 4: Initialize jQuery Croppie

Next, we need to initialize jQuery Croppie. We can do this by adding the following code to our project’s main layout file:

Step 5: Handle Image Upload

Next, we need to handle the image upload. We can do this by adding the following code to our project’s main layout file:

Step 6: Handle Image Crop

Next, we need to handle the image crop. We can do this by adding the following code to our project’s main layout file:

Step 7: Save the Cropped Image

Finally, we need to save the cropped image. We can do this by adding the following code to our project’s main layout file:

input->post(‘image’)){ $image = $this->input->post(‘image’); $imageName = time().’_cropped.png’; $config[‘image_library’] = ‘gd2’; $config[‘source_image’] = $image; $config[‘new_image’] = ‘./uploads/’.$imageName; $config[‘maintain_ratio’] = FALSE; $config[‘width’] = 200; $config[‘height’] = 200; $this->load->library(‘image_lib’, $config); $this->image_lib->resize(); } ?>

And that’s it! We have successfully implemented image crop and resize before save in Codeigniter 4 using jQuery Croppie.
[ad_1]

To crop & resize and save images using jQuery croppie with ajax in ci 4; In this tutorial, we will show you how to crop and resize images before uploading/saving to the database & directories in CodeIgniter using jQuery Croppie with ajax.

Codeigniter 4 Crop & Save Image using jQuery Croppie Example Tutorial

Use the below-given steps to crop, resize and save images using jquery with ajax in PHP CodeIgniter:

  • Step 1: Download Codeigniter Project
  • Step 2: Basic Configurations
  • Step 3: Create a Database With Table
  • Step 4: Setup Database Credentials
  • Step 5: Create a Controller
  • Step 6: Create a View
  • Step 7: Start the 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 a 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 a 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 a View

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

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

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

Conclusion

That’s all; In this tutorial, You have learned how to crop and resize image before upload in CodeIgniter 4 projects using jQuery croppie with ajax with preview.

Recommended Codeigniter Posts

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

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00