Crop and Save Image using jQuery Coppie in Codeigniter 4

Crop and Save Image using jQuery Coppie in Codeigniter 4

In this tutorial, we will teach you how to crop and resize images before uploading or saving them to the database in CodeIgniter. We’ll be using jQuery croppie with ajax to do this.

We’ll show you how to use jQuery for image upload with ajax in your Codeigniter 4 project. We’ll also show you how to preview the cropped and resized image before saving it into the database and folder. You can do all of this without refreshing or reloading the entire webpage of your CodeIgniter 4 application.

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:

  • Download Codeigniter Latest

  • Basic Configurations

  • Create Database With Table

  • Setup Database Credentials

  • Create Controller

  • Create Views

  • Start Development server

  • Conclusion

Download Codeigniter Latest

To get started with CodeIgniter 4, the first step is to download the latest version of the framework. You can download the framework from the official CodeIgniter website at https://codeigniter.com/download.

Once you have downloaded the CodeIgniter 4 setup, unzip the archive and save it in your local system. You can save it in the XAMPP/htdocs/ directory if you are using XAMPP as your local development environment.

Basic Configurations

Now, we need to configure some basic settings in the “app/config/app.php” file. To do this, we will open the “config.php” file located in the “application/config” folder using a text editor.

Set Base Url Like This

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

Create Database With Table

Now we need to create a database with the name ‘demo’. To do this, we’ll open PHPMyAdmin and create a new database with that name.

Once you’ve successfully created the database, you can use the following SQL query to create a ‘crop_images’ table within the 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;

Setup Database Credentials

Now, we need to connect our CodeIgniter 4 project to the database. To do this, we will open the “database.php” file located in the “app/Config” folder using a text editor.

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,
];

Create Controller

Next, let’s go to the ‘app/Controllers’ folder and create a new controller named ‘CropImageUpload.php’. Within this controller, we’ll create two methods or functions:

  • The ‘Index()’ function is used to display the crop image form before uploading.

  • The ‘Store()’ function is used to validate the file or image on the server-side and then store the cropped image into both the MySQL database and a 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);

    }
}

Create Views

Now, let’s create a new file named ‘crop-image-upload-form.php’ within the ‘application/views/’ folder. To do this, simply create a new file and save it with that name.

Next, copy and paste the following HTML code into the new file:

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

After creating the ‘crop-image-upload-form.php’ file, add the following code to allow users to crop the image before uploading it. This code will display a Bootstrap 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");
});

After this, we need to add below ajax code in the crop-image-upload-form.php to 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 - Torque Programming</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 & 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>