CodeIgniter 4 Image Crop with jQuery Croppie Tutorial

Last Updated on by in CodeIgniter

In this Codeigniter tutorial, you will learn how to crop an image before uploading to the server using jQuery Croppie plugin not only but also how to store the cropped image in database using AJAX request.

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.

Cropping is the process of removing the unnecessary areas from an image. Cropping is usually done to remove the needless areas of an image. It takes out the useless stuff from the picture and enhances its framing, and it even changes the aspect ratio.

Codeigniter 4 Crop Image Before Upload Example

This tutorial will explain respectively how to crop an image with croppie plugin, how to show the image preview of cropped image and also you will learn the profound way to save or store the cropped image in the database.

To accomplish the defined task you will follow the MVC approach, so you will create two routes which will perform the HTTP POST and GET requests, create a controller where image uploading code resides lastly we will bind all the logic to view and display the crop image component right there.

Create Codeigniter Project

The first step of this tutorial begins with installing the latest Codeigniter application using composer package, so make sure you have composer installed on your development machine.

composer create-project codeigniter4/appstarter

Once the initial Codeigniter application is installed, then give it a name of your choice. For example :- codeigniter-crop-image

Move to project root:

cd codeigniter-crop-image

Nonetheless, you also have another option. You can directly download the Codeigniter application from the official website.

Create Database Connection

To make the database connection open the app/Config/Database.php file, further add the database name, username and password simultaneously:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'db_name',
        '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,
	];

If you are working on local development server either MAMP or XAMPP so don’t forget to define the following value for the hostname property in app/Config/Database.php:

# MAMPP
public $default = [
  ...
     'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
  ...
]

# XAMPP
public $default = [
  ...
     'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
  ...
]

Create Table in Database

You need to create a table in the database with some columns for storing the image files in the database. Head over to the PHPMyAdmin and execute the following SQL query in the SQL section:

CREATE TABLE upload_images (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(150) NOT NULL COMMENT 'Name',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='database table' AUTO_INCREMENT=1;

Create New Controller

A controller is the file that holds the logic for storing and showing the image crop, image storage component in Codeigniter. Head over to the app/Controllers path and create an ImageCrop.php file.

Finally, add the following code in app/Controllers/ImageCrop.php:

<?php 

namespace App\Controllers; 
use CodeIgniter\Controller;
 
class ImageCrop extends Controller
{

    public function index()
    {
        return view('home');
    }
 
    public function store()
    {  
        helper(['form', 'url']);
         
        $database    = \Config\Database::connect();
        $db = $database->table('upload_images');
 
        $data = $_POST["image"];
 
        $img_arr_a = explode(";", $data);
        $img_arr_b = explode(",", $img_arr_a[1]);
 
        $data = base64_decode($img_arr_b[1]);
        $img_name = time();
 
        file_put_contents($img_name, $data);
        $img_file = addslashes(file_get_contents($img_name));
 
        $store = $db->insert(['name' =>  $img_file]);
 
        $response = [
          'success' => true,
          'data' => $store,
          'msg' => "Cropped image successfully uploaded"
         ];
     
        return $this->response->setJSON($response);
    }    
  
}

Define Route

This step shares with you about creating a route with the GET method to bring image crop component in view, so head over to app/Config/Routes.php file and append the following route code:

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/


$routes->get('/crop-image', 'ImageCrop::index');
$routes->match(['get', 'post'], 'ImageCrop/store', 'ImageCrop::store');

Setting Up Codeigniter View

Further, head over to the app/Views directory; inside here, you need to create a home.php file.

This file will invoke the view for image upload and crop component, also add the following code in app/Views/home.php file:

<html>

<head>
    <meta name="description" content="The small framework with powerful features">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Codeigniter 4 Image Crop with jQuery Croppie Example</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
</head>

<body>
    <div class="container mt-4">
        <input type="file" name="file" id="img-crop" accept="image/*" />
    </div>

    <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">
                    <h4 class="modal-title">Crop and Resize Image</h4>
                </div>
                <div class="modal-body">
                    <div id="img_prev" style="width:400px;"></div>
                    <button class="btn btn-primary btn-block crop_my_image">Store</button>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.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>
    <script>
        $(document).ready(function () {
            $image_crop = $('#img_prev').croppie({
                enableExif: true,
                viewport: {
                    width: 220,
                    height: 220,
                    type: 'circle' // square
                },
                boundary: {
                    width: 320,
                    height: 320
                }
            });

            $('#img-crop').on('change', function () {
                var reader = new FileReader();
                reader.onload = function (event) {
                    $image_crop.croppie('bind', {
                        url: event.target.result
                    }).then(function () {
                        
                    });
                }
                reader.readAsDataURL(this.files[0]);
                $('#imageModel').modal('show');
            });

            $('.crop_my_image').click(function (event) {
                $image_crop.croppie('result', {
                    type: 'canvas',
                    size: 'viewport'
                }).then(function (response) {
                    $.ajax({
                        type: 'post',
                        url: "<?php echo base_url('ImageCrop/store'); ?>",
                        data: {
                            "image": response
                        },
                        success: function (data) {
                            console.log(data);
                            $('#imageModel').modal('hide');
                        }
                    })
                });
            });
        });
    </script>
</body>

</html>

To create the basic UI Import the bootstrap CSS on top in home template, also import the croppie CSS.

Define the input file type, assign name, id over and above that accept tag.

Next, define the bootstrap modal popup and overlay component code right after the file input.

Define the required JavaScript libraries for enabling bootstrap modules, most importantly for croppie file crop plugin.

Finally, define the croppie configurations, AJAX method with file upload API to crop and store the cropped image in the database.

Start Project

Ultimately, it’s time to run the project and see how to crop image in codeigniter app and save in the database using AJAX POST request.

php spark serve

Open the below URL in the browser:

http://localhost:8080/crop-image

Codeigniter crop and save image with the help of jQuery Croppie plugin tutorial is over, and we reckon this step by step tutorial with example will help you.