Codeigniter 4 Resize Image Before Upload Example

Codeigniter 4 image resize and manipulation example; In this tutorial, i will show you how to resize image before upload to server in codeigniter 4 app.

If you want to manipulate the image before uploading the image to the server. Like resizing images, Image watermarking ,creating thumbnails, cropping images, rotating images, and much more. So you can do it by using inbuilt library of codeigniter 4.

Codeigniter 4 has been provide a library, which is used to image resizing, thumbnail creation, image cropping, image rotating, even more, image watermarking.

CodeIgniter 4 image manipulation and compress image size example; I will help you build the feature through which you can reduce image size, assume if you upload a one mb file, then you can lower down the size of the image and upload the compressed image file to the server.

Codeigniter 4 Resize Image Before Upload Example

Let’s use the following steps to resize, manipulate, compress, image size before upload to server in codeIgniter 4 apps:

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller Class
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to 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';
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create database and table; so open your phpmyadmin and execute the following sql query on it to create table:

CREATE TABLE profiles (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'File Name',
    type varchar(255) NOT NULL COMMENT 'File Type',
    PRIMARY KEY (id)

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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,

Step 5 – Create Controller Class

Create ImgManipulationController.php file. So, visit app/Controllers directory and create ImgManipulationController.php.Then add the following code into it:

namespace App\Controllers;

use CodeIgniter\Controller;

class ImgManipulationController extends Controller
  public function index() { 
    return view('home');
 public function upload() {
      helper(['form', 'url']); 

      $database = \Config\Database::connect();
      $db = $database->table('profiles');
      $validateImg = $this->validate([
          'file' => [
      if (!$validateImg) {
          print_r('Eiter file type or size (Max 4MB) not correct.');
      } else {
          $x_file = $this->request->getFile('file');
          $image = \Config\Services::image()
              ->resize(100, 100, true, 'height')
              ->save(FCPATH .'/images/'. $x_file->getRandomName());

          $x_file->move(WRITEPATH . 'uploads');

          $fileData = [
              'name' =>  $x_file->getName(),
              'type'  => $x_file->getClientMimeType()

          $store = $db->insert($fileData);
          print_r('Image resized and stored.');

  • The index() function renders image resize and compress template into the view.

Step 6 – Create Views

Create home.php view file, so visit app/views/ directory and create home.php file. Then add the following HTML into home.php file:

<!DOCTYPE html>

    <title>Codeigniter Image Manipulation Example</title>
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">


    <div class="container mt-5" style="max-width: 550px">
       <h2 class="mb-4 text-center">Codeigniter Compress Image Size using Image Manipulation Class</h2>

        <form method='post' action='<?php echo base_url(); ?>/ImgManipulationController/upload'

            <div class="form-group">
                <label for="formFileLg" class="form-label">Select image :</label>
                <input class="form-control form-control-lg" type="file" name="file">

            <div class="d-grid mt-3">
                <input type="submit" value="Upload Image" class="btn btn-outline-primary" />



Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->get('/', 'ImgManipulationController::index');

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:





Size compression or resizing the image size is essential. If you add this feature to your application, your user will have the liberty to compress the image size or resize the image size in the CodeIgniter app.

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. Codeigniter 4 Image Crop and Save using Croppie Example
  16. Dependent Dropdown using jQuery Ajax in Codeigniter 4
  17. CodeIgniter 4 Rest Api CRUD Example
  18. Codeigniter 4 Login Registration and Logout Example
  19. Get Address from Latitude and Longitude in Codeigniter 4
  20. Codeigniter 4 Google Column Charts Example

Leave a Comment