Codeigniter 4 Resize Image and Create Thumbnail Tutorial

A thorough, systematic, and practical CodeIgniter 4 image resize tutorial, in this extensive guide, will eloquently teach you how to resize the image before uploading a similarly create image thumbnail in the Codeigniter application using the image manipulation class from the beginning.

This Codeigniter image uploads and resize example is for those who have a passion for web development in Codeigniter. We can guarantee you we will take on an educational trip through the curiosities of the database interactions with the Codeigniter app, enlighten you on controller, view, and route.

In order to compress image size in Codeigniter, we have done the proper assortment of instructions. Each instruction solves a specific problem and takes you closer to build the image resize functionality with the image manipulation class.

Image manipulation is not just an ordinary class; instead, it’s a gold mine of features related to modifying the image. Here are couple of things you can do with this magical class:

  • Image Resizing
  • Thumbnail Creation
  • Image Cropping
  • Image Rotating
  • Image Watermarking

Codeigniter 4 Resize Image, Generate Thumbnail using Image Manipulation Class Example

  • Step 1: Install New Codeigniter App
  • Step 2: Add CI App to Database
  • Step 3: Create New Table with SQL Query
  • Step 4: Set Up Controller File
  • Step 5: Add Routes in Route File
  • Step 6: Create and Set up View File
  • Step 7: Run App in Browser

Install New Codeigniter App

Downloading a Codeigniter app is easy; you can simply download it Codeigniter from:

https://www.codeigniter.com/download

Next, Unzip the package, change the project’s name, and keep Codeigniter files and folder in your server directory.

Another way is to download the app is by the Composer command.

composer create-project codeigniter4/appstarter

Add CI App to Database

After you have successfully install the brand new codeigniter app, its time to make the app connection with database.

Open app/Config/Database.php and enter your username, password, and database name.

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

Create New Table with SQL Query

If anyhow you haven’t created a database, create a database, select it

Then, run the following SQL query to create the table with column names to store the uploaded file information.

CREATE TABLE clients (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    file_name varchar(255) NOT NULL COMMENT 'Name',
    file_type varchar(255) NOT NULL COMMENT 'File',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

Set Up Controller File

A controller is not just a file but a single mighty class that contains the methods and logic to accomplish the programming related task.

To resize an image in Codeigniter, you need to create altogether a controller class.

After creating the file, append the provided code in app/Controllers/ImgResizeController.php.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;


class ImgResizeController extends Controller
{
    
  public function index() { 
    return view('client');
 }
   
 public function store() {
      helper(['form', 'url']); 

      $database = \Config\Database::connect();
      $db = $database->table('clients');
   
      $fileValidation = $this->validate([
          'file' => [
              'uploaded[file]',
              'mime_in[file,image/png,image/jpg,image/jpeg,image/gif]',
              'max_size[file,4096]',
          ]
      ]);
       
      if (!$fileValidation) {
          print_r('Max 4mb file size is allowed.');
      } else {
          $isFile = $this->request->getFile('file');
          $image = \Config\Services::image()
              ->withFile($isFile)
              ->resize(150, 150, true, 'height')
              ->save(FCPATH .'/thumbnail/'. $isFile->getRandomName());

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

          $fileData = [
              'file_name' =>  $isFile->getName(),
              'file_type'  => $isFile->getClientMimeType()
          ];

          $store = $db->insert($fileData);
          print_r('Image has resized and thumbnail been generated!');
      } 
 }

}

Validate image before uploading to server; the validation contains image file type validation, file size validation upto 4MB.

After validating the image file with the image manipulation, the manipulation class resizes the image in the Codeigniter app. Similarly, generating the image thumbnail and storing it into the server and locally into the uploads folder.

Add Routes in Route File

The purpose of route formation is to execute the code we added into the controller class; the new routes will validate the image, resize the image, compress the image size, and save the image into the database.

Add code in app/Config/Routes.php.

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

$routes->setDefaultController('ImgResizeController');

$routes->get('/resize-image', 'ImgResizeController::index');

Create and Set up View File

The view file is used to present the feature on the browser visually; to display the file upload component, you have to create a view file.

To design the UI component, we can use Bootstrap CSS, add the CSS link on the top, create a form tag, tie it to the controller store method.

Update code in app/Views/client.php file.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>Codeigniter 4 Reisze Image and Generate Thumbnail Example</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

	<div class="container">
		<h2 class="mb-3">Codeigniter Compress Image Size using Image Manipulation Class</h2>

		<form action='<?php echo base_url(); ?>/ImgResizeController/store' method='post' 
		enctype='multipart/form-data'>

			<div class="form-group">
				<input class="form-control form-control" type="file" name="file">
			</div>

			<div class="mt-2">
				<input type="submit" value="Resize + Upload" class="btn btn-dark" />
			</div>
		</form>
	</div>
</body>

</html>

Run App in Browser

Running your Codeigniter app is the subsequent task; enter the provided command in the terminal, it will launch the server.

php spark serve

As, you remember we have to generate thumbnail after resizing, don’t forget to create a ‘thumbnail’ folder for saving the resized images.

Check your thumbnails on the app/Public/thumbnail folder:

Make sure to use the given url to view your application.

http://localhost:8080/resize-image

Codeigniter 4 Resize Image and Create Thumbnail Tutorial

Summary

In this profound guide, we, bit by bit, learned how to resize image size in Codeigniter using image manipulation. We taught you how to incorporate image manipulation in the controller class, resize the image by defining the custom image size. Most importantly, how to upload the image to the database after resizing and validating the image with the help of the controller, route, and view file.

We suppose this guide will be helpful and ramp up your skills in Codeigniter development.