Codeigniter 4 Image Rotate, Upload, and Validation Tutorial

Last updated on: by Digamber

Codeigniter 4 image manipulation tutorial; In this tutorial, we would like to show you how to build an image upload functionality, rotate an image after uploading, and resize an image in Codeigniter 4 application with the help of the CodeIgniter image manipulation class.

This is the second tutorial of the image manipulation series; in the previous tutorial, we shared how to set up file upload, add file validation, use the image manipulation service in Codeigniter.

In this Codeigniter image rotate example, you will see how to use the image manipulation service to rotate the image, save the image to create a rotated thumbnail, including resizing the image.

We will use the rotate image in CodeIgniter using the rotate() method; it is available through the image manipulation class. It allows you to quickly rotate an image in ‘90’, ‘180’, and ‘270 degree, respectively.

Codeigniter 4 Image Rotate and Upload Example

  • Step 1: Set Up Codeigniter App
  • Step 2: Error Handling
  • Step 3: Create Files Table
  • Step 4: Add Database Credentials
  • Step 5: Set Up Controller
  • Step 6: Create Route
  • Step 7: Build File Upload View
  • Step 8: Test Codeigniter App

Set Up 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.

Error Handling

This step is optional, you can activate the error debugging. You need to go to app/Config/Boot/development.php likewise app/Config/Boot/production.php files and carefully switch the display_errors property to 1 from 0.

ini_set('display_errors', '1');

Create File Table

We will not just rotate the image but also validate the image file and store it in the database; for storing the image, we need a database and a files table.

Make sure to execute the following SQL query to generate a new table.

CREATE TABLE files (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    type varchar(255) NOT NULL COMMENT 'File Type',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='files table' AUTO_INCREMENT=1;

Add Database Credentials

In this segment, you have to open the app/Config/Database.php and add the database name, username, and password in the $default array.

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

Sometimes, you might face following error:

Unable to connect database: Codeigniter;

To fix this error, you need to define the hostname based on your localhost development server.

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

Set Up Controller

Subsequently, you have to create a brand new file in the app/Controllers folder, and It might be named ImgManipulationController.php.

Furthermore, go to app/Controllers/ImgManipulationController.php and add the given code recklessly.

<?php
namespace App\Controllers; 
use CodeIgniter\Controller;
    
class ImgManipulationController extends Controller {
   public function index() { 
      return view('image');
   }
    
   public function upload() {
        
        helper(['form', 'url']); 
        // database
        $database = \Config\Database::connect();
        $db = $database->table('files');
    
        // file validation
        $isValidFile = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file,image/jpg,image/jpeg,image/png,image/gif]',
                'max_size[file,4096]',
            ]
        ]);
        
        if (!$isValidFile) {
            print_r('Upload valid file or image size should be upto 4mb');
        } else {
            $imgPath = $this->request->getFile('file');
            // Image manipulation
            $image = \Config\Services::image()
                ->withFile($imgPath)
                ->fit(150, 150, 'left')
                ->rotate(90)
                ->save(FCPATH .'/thumbnails/'. $imgPath->getRandomName());
            $imgPath->move(WRITEPATH . 'uploads');
            $fileData = [
                'name' =>  $imgPath->getName(),
                'type'  => $imgPath->getClientMimeType()
            ];
            $store = $db->insert($fileData);
            print_r('File successfully uploaded.');
        } 
   }

} ?>

Let me explain what is being done in the controller file:

The index() function showing the file upload form, which we will design using Bootstrap 5.

The upload() method conjugates unbound processes, file validation, access to database and table, adding file validation, resizing the image and creating rotate image functionality and creating or generating the thumbnails.

Don’t forget to create the 'thumbnails' folder in the 'public' directory; here, you can save the resized images and the thumbnails.

Similarly, create the 'uploads' folder in 'writable' folder; you can see these folder updated after uploading the images.

Create Route

To make the file upload template your default view, you need to define the route for that, ensure that you update the following code in the app/Config/Routes.php file.

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

$routes->setDefaultController('ImgManipulationController');
$routes->get('/', 'ImgManipulationController::index');
$routes->match(['get', 'post'], 'ImgManipulationController/upload', 'ImgManipulationController::upload')

Build File Upload View

Ultimately, we have landed on the final step of this tutorial, and we need to set up a new view, so create the image.php file in the app/Views folder. Thereafter, open and update the app/Views/image.php file.

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter Image Manipulation Demo</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: 500px">
       <h2 class="mb-4 text-center">Codeignter 4 Rotate Image Example</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">Choose 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-danger" />
            </div>
        </form>
    </div>
</body>
</html>

Test Codeigniter App

Now, we have completed the tutorial, finally we will run the app and show you how to rotate, resize and upload the image to the database.

php spark serve

Use the url to check the app.

http://localhost:8080

Codeigniter Rotate Image

Conclusion

The Codeigniter 4 image rotate tutorial is ended; in this quick guide, we tried to explain briefly and swiftly how to create an image uploading feature, how to manipulate an image that contains resizing the image and rotating the image.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.