Codeigniter 4 Resize Image with Image Manipulation Tutorial

Last updated on: by Editorial Team

Codeigniter 4 image resize size tutorial; This detailed guide explains how to easily create image upload and compress image file size in the Codeigniter app using the image manipulation class.

Codeigniter’s 4 image manipulation class allows you image resizing, thumbnail creation, image cropping, image rotating, even more, image watermarking. First, you need to initialize the class for image uploading and resizing images.

As the term suggests, to make something fill smaller space than typically. This standard guide will justify the purpose of compress, in the same way, describe how to make image files smaller in size; consequently, they will acquire smaller space.

This Codeigniter compress image size example 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.

In this tutorial, you will learn how to use the image_lib library in Codeigniter to compress the image file size, no matter what the image type is, be it jpg, jpeg, png, or gif.

Codeigniter 4 Image Upload and Compress Image Size Example

  • Step 1: Create Codeigniter App
  • Step 2: Enable Error Handling
  • Step 3: Create Files Table
  • Step 4: Connect to Database
  • Step 5: Create Image Resize Controller
  • Step 6: Add New Route
  • Step 7: Create File Upload Form
  • Step 8: Test Codeigniter App

Create Codeigniter App

Composer is required if you want to install the Codeigniter application and begin the web development in the Codeigniter environment. Enough talking, let’s execute the command to start installing the app.

composer create-project codeigniter4/appstarter

A new app has been downloaded, now make sure to change codeigniter app’s name.

There is also a simple method, in which you need to visit the CI site and from there you can download the Codeigniter app directly from their official website.

Enable Error Handling

Error debugging needs to be enabled, get to the app/Config/Boot/development.php likewise app/Config/Boot/production.php files. Change the display_errors property value to 1 from 0.

ini_set('display_errors', '1');

Create File Table

To store the resized image files in the database requires you to create the table in the database. Thus, ensure that you have executed the following SQL query and created a new table with id, name, and file type values.

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)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Profiles table' AUTO_INCREMENT=1;

Connect to Database

In this step, or from this discourse, we explain how to create the mutual consensus between CI app or MySQL database, consequently add the database name, username, and password in the app/Config/Database.php.

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

CodeIgniter\Database\Exceptions\DatabaseException

If you are skeptical about the Unable to connect database: Codeigniter error; then make sure you have added the either of the hostname in the db connection $default variable.

# ====== MAMP
public $default = [
  ...

  'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
]

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

Create Image Resize Controller

Please create a new controller file, get to the the app/Controllers directory, create a file and name it ImgManipulationController.php.

Open app/Controllers/ImgManipulationController.php and update the given code.

<?php 
namespace App\Controllers;

use CodeIgniter\Controller;

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

      $database = \Config\Database::connect();
      $db = $database->table('profiles');
   
      $validateImg = $this->validate([
          'file' => [
              'uploaded[file]',
              'mime_in[file,image/jpg,image/jpeg,image/png,image/gif]',
              'max_size[file,4096]',
          ]
      ]);
       
      if (!$validateImg) {
          print_r('Eiter file type or size (Max 4MB) not correct.');
      } else {
          $x_file = $this->request->getFile('file');
          $image = \Config\Services::image()
              ->withFile($x_file)
              ->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 does the simple thing, and it loads the image template that we need to create in the views folder.

The upload() method processes the various tasks simultaneously; first, we accessed the database and the files table, implement the file validation with file types, and max file upload sie.

We can now use the image manipulation class; this class access the image that we are likely to upload, define the image thumbnail size using resize, and use the save() method to store the resized image into the “public/images” folder.

Create the ‘images’ folder into the ‘public’ directory; here, cropped images are kept.

Add New Route

Next, you have to create a route, which loads the file upload component into the view. Thus, open the app/Config/Routes.php and insert the given below code in the file.

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

Create File Upload Form

To compress the image, create a basic file upload form, get into the app/Views directory, there you need to create a new view file, name it image.php furthermore insert the following code into the app/Views/image.php file.

<!DOCTYPE html>
<html>

<head>
    <title>Codeigniter Image Manipulation Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css">
</head>

<body>

    <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'
            enctype='multipart/form-data'>

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

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

</body>

</html>

Test Codeigniter App

Running a Codeigniter app is necessary to test the app; you can start the app using a single command.

php spark serve

Finally, run the app with the help of the given url.

http://localhost:8080

Codeigniter resize image example

Conclusion

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.

The Codeigniter compress image size tutorial is completed, and we have explained immaculately how to upload an image file in Codeigniter and resize the image file size in Codeigniter.