CodeIgniter 4 Image Text Overlay Watermarking Tutorial

Last Updated on by in CodeIgniter

Codeigniter 4 image watermarking tutorial; In this detailed guide, we will explain how to add text watermarking on the image in the CodeIgniter 4 application with the help of the CodeIgniter’s default image manipulation class.

Let us understand what image watermarking is; ideally, image watermarking adds a digital signature onto the image files.

Theoretically, its a pragmatic approach from copyright protection, on top of that content identification perspective.

This step-by-step tutorial shows you how to upload image similarly to create image watermarking functionality to add digital signature on the image using the image manipulation class.

Codeigniter’s image manipulation class is the iron man among avengers, and it helps you customize the image. Not just image watermarking but it also allows following process:

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

Codeigniter 4 Image Upload and Text Overlay Watermark Example

  • Step 1: Install Codeigniter Project
  • Step 2: Turn On Error Handling
  • Step 3: Create Files Table in Database
  • Step 4: Connect App to Database
  • Step 5: Create and Set Up Controller
  • Step 6: Register New Route
  • Step 7: Create Image Upload View
  • Step 8: Start CI Application

Install Codeigniter Project

The first method is to download the CodeIgniter project is to set up composer on your system and run the following command.

composer create-project codeigniter4/appstarter

The second method is less complicated, just visit the CI site and download the latest version of the Codeigniter application.

Turn On Error Handling

In codeigniter you have to turn on the error handling by setting up display_errors property to 1 from 0, make sure to change the values in app/Config/Boot/development.php and app/Config/Boot/production.php files.

ini_set('display_errors', '1');

Create File Table in Database

This section will show you how you can swiftly create a new files table, which will help you store the image files data.

Run the following SQL query from the PHPMyAdmin tab.

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;

Connect App to Database

It is inevitable to add the database name, username, and password in the app/Config/Database.php file; it makes the connection and consent between CodeIgniter and database.

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

If you are a Mac user or anyhow getting the CodeIgniter\Database\Exceptions\DatabaseException or Unable to connect database: Codeigniter errors. Then, you can follow the given below instruction to get rid of the mentioned issues.

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

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

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

Create and Set Up Controller

Next, you require to create ImgManipulationController.php file in app/Controllers folder.

Then, head over to app/Controllers/ImgManipulationController.php and add the add the given code.

You have to create the 'images' folder inside the 'public' folder; The public/images directory will hold the uploaded and watermarked file. Also, create the 'uploads' folder in 'writable' path; eventually, you may see these folder updated after successfully uploading the image files.

<?php

namespace App\Controllers; 
use CodeIgniter\Controller;
    
class ImgManipulationController extends Controller {

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

        // access 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]',
            ]
        ]);
        
        // check validation
        if (!$isValidFile) {
            print_r('Upload valid file upto 4mb size');
        } else {
            $imgPath = $this->request->getFile('file');

            // Image manipulation
            $image = \Config\Services::image()
                ->withFile($imgPath)
                ->text('Copyright Positronx @2021', [
                    'color'      => '#fff',
                    'opacity'    => 0.7,
                    'withShadow' => true,
                    'hAlign'     => 'center',
                    'vAlign'     => 'bottom',
                    'fontSize'   => 20
                ])
                ->save(FCPATH .'/images/'. $imgPath->getRandomName());

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

            $fileData = [
                'name' =>  $imgPath->getName(),
                'type'  => $imgPath->getClientMimeType()
            ];

            $store = $db->insert($fileData);
            print_r('File uploaded successfully.');
        } 
   }


} ?>

We used the text() method to add text watermark on the image very efficiently; the text() method offers different kinds of audacity, which helps show the copyright information, some brand name, etc.

The initial or first argument refers to the text that needs to be shown over the image, whereas the second parameter sets up the customization for image watermarking.

Here are the options offered by image manipulation class you may use for customization:

  • color Text Color (hex number), i.e., #ff0000
  • opacity A number between 0 and 1 that represents the opacity of the text.
  • withShadow Boolean value whether to display a shadow or not.
  • shadowColor Color of the shadow (hex number)
  • shadowOffset How many pixels to offset the shadow. Applies to both the vertical and horizontal values.
  • hAlign Horizontal alignment: left, center, right
  • vAlign Vertical alignment: top, middle, bottom
  • hOffset Additional offset on the x axis, in pixels
  • vOffset Additional offset on the y axis, in pixels
  • fontPath The full server path to the TTF font you wish to use. System font will be used if none is given.
  • fontSize The font size to use. When using the GD handler with the system font, valid values are between 1-5.

Register New Route

In this essential step, we will bind the controller to view, trigger the index() method that we defined in the controller for loading the view file, add the 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')

Create Image Upload View

You can create the file upload form within minutes and use the bootstrap form control module. But first, add the bootstrap CSS path at the top part of the page, pass the controller with the method in action to start the image upload and watermarking process.

Now, we require to create view file, move towards the app/Views/ path and create image.php file within the folder.

Next, add the code app/Views/image.php file.

<!DOCTYPE html>
<html>

<head>
    <title>Codeigniter Adding Overlays Watermarks on Images 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: 500px">
       <h2 class="mb-4 text-center">Codeigniter 4 Image Upload with Text Watermark 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">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" class="btn btn-outline-primary" />
            </div>
        </form>
    </div>

</body>

</html>

Start CI Application

In the final segment, we will show you how to start the Codeigniter application. But first, make sure to open the terminal and execute the command.

php spark serve

Finally, you can test the application using the suggested url.

http://localhost:8080

Codeigniter 4 Image Watermark

Conclusion

We have successfully completed the CodeIgniter image manipulation tutorial; in this example, we explored how to add a text watermark on the image after upload and store the image in the public directory also in the database; we reckon you liked our efforts.