Codeigniter 4 Watermark Image Example

In this example, we will show you how to add watermark to an image in Codeigniter 4.

Step 1: Create a Controller

Create a controller file Watermark.php in the app/Controllers folder and add the following code in it.

load->library(‘image_lib’); // Set the configuration for watermarking $config[‘source_image’] = ‘./assets/images/image.jpg’; $config[‘wm_text’] = ‘CodeIgniter 4’; $config[‘wm_type’] = ‘text’; $config[‘wm_font_path’] = ‘./assets/fonts/arial.ttf’; $config[‘wm_font_size’] = ’20’; $config[‘wm_font_color’] = ‘ffffff’; $config[‘wm_vrt_alignment’] = ‘middle’; $config[‘wm_hor_alignment’] = ‘center’; // Load the image library with the configuration $this->image_lib->initialize($config); // Watermark the image $this->image_lib->watermark(); // Display the watermarked image echo ‘‘; } }

Step 2: Create a View

Create a view file index.php in the app/Views folder and add the following code in it.

Codeigniter 4 Watermark Image Example

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

How to add watermark images using codeigniter 4 php framework

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

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

Step 1 – Setup 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 a 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/[email protected]/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 – Define 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.

Recommended CodeIgniter Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?