Codeigniter 4 Watermark Image Example
Codeigniter 20-Dec-2021

Codeigniter 4 Watermark Image Example

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

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

Codeigniter 4 Image Text Overlay Watermarking Example

Follow the following steps and you can easily add text overlay watermark on images in codeigniter 4 apps:

  • Step 1 – Download Codeigniter Latest
  • Step 2 – Basic Configurations
  • Step 3 – Create Database With Table
  • Step 4 – Setup Database Credentials
  • Step 5 – Create Controller
  • Step 6 – Create Views
  • Step 7 – Add Routes
  • Step 8 – Start Development server

Step 1 – Download Codeigniter Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2 – Basic Configurations

Next, you will set 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';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database With Table

In this step, you need to create a database name demo, so open PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a crop_images table in your database.

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',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;

Step 4 – Setup Database Credentials

In this step, you need to connect our project to the database. So, visit app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, YOU need to set up database credentials in this file like below.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];

Step 5 – Create Controller

In this step, Go to app/Controllers and create a controller name ImageUploadController.php. Then add the following code into it:

<?php
 
namespace App\Controllers; 
use CodeIgniter\Controller;
     
class ImageUploadController extends Controller {
 
   public function index() { 
      return view('imageUploadForm');
   }
     
   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 Tutsmake.com @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.');
        } 
   }
 
} ?>

Step 6 – Create Views

In this step, you need to create imageUploadForm.php, go to application/views/ directory and create imageUploadForm.php file. and update the following HTML into your files:

<!DOCTYPE html>
<html>
 
<head>
    <title>Codeigniter Adding Overlays Watermarks on Images Example - Tutsmake.com</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(); ?>/ImageUploadController/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>

Step 7 – Add Routes

In this step, visit app/Config/ directory and open Routes.php file. Then define in the routes in this file, as shown below:

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/
 
$routes->setDefaultController('ImageUploadController');
 
$routes->get('/', 'ImageUploadController::index');

Step 8 – Start Development server

For start development server, open your terminal and execute the following command it:

php spark serve

Then, Go to the browser and hit below the URL:

http://localhost:8080

Conclusion

Codeigniter 4 image watermarking example. In this tutorial guide, you have learned how to add text watermarking on the image in the CodeIgniter 4 application with the help of the CodeIgniter’s default image manipulation class.