Codeigniter 4 Crop Image and Generate Thumbnails Tutorial

Codeigniter crop image before upload tutorial; In this eloquent guide, we will methodically, systematically, not only but also simply teach you how to crop and resize an image before upload in Codeigniter using the jQuery Croppie library. Also, we will cover how to save resized images into the MySQL database.

This article is the compendium of useful instruction, which will help us discover how to generate an image thumbnail in the Codeigniter app using the JavaScript Croppie package.

We will use the Croppie plugin to resize the image before uploading it to the server. Rest assured, we will learn all the methodologies required behind the creation of Codeigniter image crop functionality.

Image cropping is the primary feature that web developers have to create. To build this significant feature, you have to be familiar with PHP, HTML, CSS, and JavaScript.

If you have a prior understanding of these technologies, stick to this tutorial until the last step. This example of Codeigniter crop image covers almost all the essential concepts one by one.

Croppie is a fast, easy to use image cropping plugin with tons of configuration options!

How to Crop Image using Croppie in Codeigniter 4 App

  • Step 1: Install Codeigniter Project
  • Step 2: Generate & Insert Records in Table
  • Step 3: Connect App to Database
  • Step 4: Register New Route
  • Step 5: Add Image Crop Logic in Controller
  • Step 6: Setting Up View File
  • Step 7: Run App in Browser

Install Codeigniter Project

There are many practical tactics to create your Codeigniter app, But make sure you have constituted Composer tool in your development machine.

The second ideal tactic is to download the Codeigniter app from the official site outright.

composer create-project codeigniter4/appstarter

Generate & Insert Records in Table

This tutorial will be unfinished until we constituted a new table in the database.

Execute the given SQL command, and create the table with righteous intentions.

CREATE TABLE profile (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    file_name varchar(150) NOT NULL COMMENT 'File Name',
    created_on varchar(20) NOT NULL COMMENT 'Date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='New table' AUTO_INCREMENT=1;

Connect App to Database

As you can see, the compendium of code holding the database name, username, and password details, similarly you have to enclose these values to form the coherence between app and database.

Update app/Config/Database.php file.

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

Register New Route

It takes only a few lines of code to build a route systematically.

Hence, define the route method and pass the route and controller name and method in app/Config/Routes.php file.

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


$routes->setDefaultController('ProfileController');
$routes->get('/crop', 'ProfileController::index');
$routes->match(['get', 'post'], 'ProfileController/onScrollLoadMore', 'ProfileController::onScrollLoadMore');

Add Image Crop Logic in Controller

The form helper and insert() query methods allow you to store the thumbnail in the database after cropping or generating the image.

So, let’s unlock the potentials by adding the code into app/Controllers/ProfileController.php file.

<?php 

namespace App\Controllers;

use CodeIgniter\Controller;


class ProfileController extends Controller
{

    public function index()
    {
        return view('index');
    }
 
    public function cropImage()
    {  
        helper(['form', 'url']);
        
        $database    = \Config\Database::connect();
        $db = $database->table('profile');
 
        $data = $_POST["image"];

        $imgOne = explode(";", $data);
        $imgTwo = explode(",", $imgOne[1]);
        $data = base64_decode($imgTwo[1]);

        $fileName = time();
        file_put_contents($fileName, $data);
        
        $cpImg = addslashes(file_get_contents($fileName));
        $save = $db->insert(['file_name' =>  $cpImg]);
 
        $response = [
          'success' =>true,
          'data' => $save,
          'msg' => "File uploaded"
         ];
     
        return $this->response->setJSON($response);
    }    
 
}

Setting Up View File

In this final section, we will tell you how to create the image cropping interface.

We will use the Bootstrap library to make it more interactive likewise, use the jQuery Croppie CDN CSS and Script links to make this feature excessively intuitive.

Update app/Views/index.php.

<?php 

namespace App\Controllers;

use CodeIgniter\Controller;


class ProfileController extends Controller
{

    public function index()
    {
        return view('index');
    }
 
    public function cropImage()
    {  
        helper(['form', 'url']);
        
        $database    = \Config\Database::connect();
        $db = $database->table('profile');
 
        $data = $_POST["image"];

        $imgOne = explode(";", $data);
        $imgTwo = explode(",", $imgOne[1]);
        $data = base64_decode($imgTwo[1]);

        $fileName = time() . '.png';
        file_put_contents($fileName, $data);
        
        $cpImg = addslashes(file_get_contents($fileName));
        $save = $db->insert(['file_name' =>  $cpImg]);
 
        $response = [
          'success' =>true,
          'data' => $save,
          'msg' => "File uploaded"
         ];
     
        return $this->response->setJSON($response);
    }    
 
}

Once you added the recommended scripts and CSS, add the form file input and bootstrap modal, file input allows selecting the image, and the modal component will be used to implement the open the crop tool.

Run App in Browser

Each component has been constituted in this small app, and we hope you have followed every instruction attentively.

Finally, run the command to start the app and use the provided link to test the app.

After cropping the image, you can see the generated thumbnail in the app/public directory.

php spark serve
http://localhost:8080/crop

Crop image before upload in Codeigniter

Conclusion

So ultimately, you have assimilated the development process about how to crop the image before uploading it to the server in Codeigniter from scratch using the jQuery croppie library.

The jQuery packages allow us to quantify and amplify the web development process by giving us pre-cooked programming solutions. In this profound guide, we learned how to generate an image thumbnail or how to crop the image and save it into the database.

We hope we have immaculately explained every instruction mentioned in this guide; if you find any error in the programmatic compendium, be sure to inform us about the error.