Add Text Watermark on Image in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 7 minutes
2,599 Views

Adding a text watermark in image is super easy in codeigniter 4. In CodeIgniter 4 we have image processing library due to which everything like resize, rotate, crop, adding a text watermark is very easy.

While going through this article content, you will also see what extensions in php we need while working with image processing methods.

Inside this article we will learn the complete concept of adding a text watermark on image in CodeIgniter 4.

Here, we have more articles on Image manipulation Class of CodeIgniter 4.

  • Rotate Image in CodeIgniter 4, Click here.
  • Resize Image before upload to server in CodeIgniter 4, Click here.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


.env Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file.

Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Needed PHP Extension Before Work

While working with image related stuff in PHP, make sure your PHP version should have these two most common image processing libraries GD Library and Imagick extensions enabled.

Whether your system already contains these extensions or not you can verify like this –

  • Create info.php file at your localhost directory
  • <?php phpinfo(); ?> Add this code into info.php file.
  • Run this file into browser

You should see these information into php information page.

GD Extension Enabled

Imagick Extension Enabled

So, these two extensions we need, if you don’t have. Please install it first.


Create Controller

We need now a controller file. Back to terminal and run this spark command to create.

$ php spark make:controller Image --suffix

This will creates a file ImageController.php at /app/Controllers folder.

Open ImageController.php and write this complete code into it,

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class ImageController extends BaseController
{
	public function index()
	{
		if ($this->request->getMethod() == "post") {

			$rules = [
				"name" => "required|min_length[3]|max_length[40]",
				"image" => [
					"rules" => "uploaded[image]|max_size[image,1024]|is_image[image]|mime_in[image,image/jpg,image/jpeg,image/gif,image/png]",
					"label" => "Image",
				]
			];

			if (!$this->validate($rules)) {

				return view("upload-image", [
					"validation" => $this->validator,
				]);
			} else {

				$file = $this->request->getFile("image");

				$session = session();
				$image = $file->getName();

				if ($file->move("images", $image)) {

					// watermark images path
					$waterMark = "texts-images";

					// adding a watermark into image
					\Config\Services::image()->withFile('images/' . $image)
						->text('Copyright 2021 Online Web Tutor', [
							'color'      => '#fff',
							'opacity'    => 0.5,
							'withShadow' => true,
							'hAlign'     => 'center',
							'vAlign'     => 'bottom',
							'fontSize'   => 40
						])
						->save($waterMark . '/' . $image);

					// You can add your code here to save into database

					$session->setFlashdata("success", "Watermark added successfully");
				}
			}
			redirect('upload-image');
		}

		return view("upload-image");
	}
}
  • When we upload image, a text watermark will be added to image and save into a different folder.
  • So we will get two different images. Original image inside /images folder and watermark images inside /texts-images folder.

Create Layout File

Go inside /app/Views folder and create a file add-product.php. Open this file and write this complete code into it.

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

<head>
    <title>Adding a Text watermark into Images in CodeIgniter 4</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <style>
        .errors li {
            color: red;
        }
    </style>
</head>

<body>

    <div class="container">
        <h2 style="text-align: center;">Adding a Text watermark into Images in CodeIgniter 4</h2>
        <div class="panel panel-primary">
            <div class="panel-heading">Adding a Text watermark into Images in CodeIgniter 4</div>
            <div class="panel-body">

                <?php if (session()->get("success")) { ?>
                    <div class="alert alert-success">
                        <?= session()->get("success") ?>
                    </div>
                <?php } ?>

                <?php
                // To print error messages
                if (isset($validation)) {

                    print_r($validation->listErrors());
                }
                ?>

                <form action="<?= base_url('upload-image') ?>" enctype="multipart/form-data" method="post">
                    <div class="form-group">
                        <input type="text" name="name" class="form-control" placeholder="Name">
                    </div>
                    <div class="form-group">
                        <input type="file" name="image" class="form-control" class="image">
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-success">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>

</html>

Create Images Folders

We need to create two folders inside /public folder which is at root.

  • images folder inside as /public/images – It will store original images
  • texts-images inside as /public/texts-images – It will store watermark images.

Create Route

Open Routes.php from /routes folder and add this route into it.

//...

$routes->match(["get", "post"], "upload-image", "ImageController::index");

//...

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/upload-image

When we upload image, then we can see into the given image a watermark is added at the footer.

We hope this article helped you to learn Add Text Watermark on Image in CodeIgniter 4 Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5