PHP Codeigniter 4 Add Text Watermark on Image Tutorial

Do you know you? You can add an image text watermark on the image in the PHP Codeigniter 4 application, and you will only need image manipulation class to set a watermark on the image in Codeigniter 4 application.

This Codeigniter text watermark on the image example will demonstrate how to add text watermark simply. We can easily overlay a text watermark onto the image using the text() method provided by the image manipulation class.

The overlay is set on the image for various purposes; it might be used to add copyright notices, photographer names, or just marking the images for various reasons.

Furthermore, you will also learn other techniques regarding building a simple CodeIgniter app, which contains database connection, writing simple SQL queries to create a table and its properties, creating and setting up routes and controllers and incorporating all to build files upload feature with text watermarking on the image.

How to Add Watermark or Text Overlay to Image in Codeigniter 4

  • Step 1: Download Codeigniter App
  • Step 2: Generate Table in Database
  • Step 3: Connect Codeigniter to Database
  • Step 4: Register Route
  • Step 5: Set Up Controller File
  • Step 6: Build View File
  • Step 7: View App in Browser

Download Codeigniter App

If Composer is located on your machine, then without wasting time, run the following command.

composer create-project codeigniter4/appstarter

If you use the below link and execute it in the browser, this link will take you to the official site, from where you can download the latest zipped version of the Codeigniter application.

https://www.codeigniter.com/download

Ensure that you have unzipped the package and have changed the project name; make sure to keep the Codeigniter folder in your server directory.

Generate Table in Database

In order to store any data into the database, it requires a table in the database.

We decided to run the SQL query to formulate a new table with columns or properties, which will be the locus of the uploaded image file’s information.

CREATE TABLE profile (
    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;ʼ

Connect Codeigniter to Database

Codeigniter offers multiple ways to connect the application to the database, and we found the below method best.

Insert the username, password and database name in the app/Config/Database.php file.

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

Register Route

To open the app, we have to specify a particular route; this route will communicate with the controller and execute the index function, which manifests the user template on the browser.

Update the code in app/Config/Routes.php file.

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

$routes->get('/watermark-image', 'UserController::index');

Set Up Controller File

In this section, you have to create the controller file; here are the tasks we will do in the new controller file.

First, connect to the table using the connect() method.

Validate the file, check the file type and file size (only four MB limit is set).

Access the image uploaded through file form input.

Use the image manipulation’s image() method to customize the text overlay to insert a watermark on the image. You can also check out image manipulation text watermark properties.

Finally, store the image in the database as well as in the app/public/uploads folder.

Update app/Controllers/UserController.php.

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
    


class UserController extends Controller {

   public function index() { 
      return view('user');
   }
    
   public function store() {
        helper(['form', 'url']); 
        $database = \Config\Database::connect();
        $db = $database->table('profile');
    
        $checkValidation = $this->validate([
            'file' => [
                'uploaded[file]',
                'mime_in[file,image/gif,image/jpg,image/jpeg,image/png]',
                'max_size[file,4096]',
            ]
        ]);
        
        if (!$checkValidation) {
            print_r('4mb max file size allowed');
        } else {
            $getImageFile = $this->request->getFile('file');

            $image = \Config\Services::image()
                ->withFile($getImageFile)
                ->text('this image may be subject to copyright', [
                    'color'      => '#fff',
                    'opacity'    => 0.8,
                    'withShadow' => true,
                    'vAlign'     => 'top',
                    'hAlign'     => 'center',
                    'fontSize'   => 25
                ])
                ->save(FCPATH .'/uploads/'. $getImageFile->getRandomName());

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

            $data = [
                'file_name' =>  $getImageFile->getName(),
                'file_type'  => $getImageFile->getClientMimeType()
            ];

            $save = $db->insert($data);
            print_r('Image with watermark successfully uploaded to the server.');
        } 
   }


} ?>

Build View File

Here are the steps going towards defining a view file, this file will process the controller code and eloquently add the watermark on the image after uploading.

Without wasting your time, we will straight go to Views directory in the app, create the user file.

Add the code in app/Views/user.php file.

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

<head>
	<meta charset="UTF-8">
	<title>Codeigniter 4 Add Text Overlay to Image File Example</title>
	<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

	<div class="container">
		<form action="<?php echo base_url(); ?>/UserController/store"
			enctype="multipart/form-data" method="post">

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

			<div>
				<input type="submit" value="Store" class="btn btn-dark" />
			</div>
		</form>
	</div>
</body>

</html>

View App in Browser

We have completed with the development, Lastly, start the application with the help of the php spark command.

After running the command, copy the provided url paste in the browser and hit enter to watermark the image.

php spark serve
http://localhost:8080/watermark-image

PHP Codeigniter 4 Add Text Watermark on Image Tutorial

Conclusion

In this tutorial, we learned how to watermark an image using the image manipulation text method simply; we had a look at the text overlay customization features, draw the text watermark on the image and store the image on the local app’s folder and onto the server.

So, this incredible journey of the Codeigniter 4 image watermarking tutorial has ended.