Codeigniter 4 Image Watermark Tutorial Example

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

In this watermark on image in CodeIgniter 4 tutorial; i will create a simple image upload form and add text watermark on image before upload to server directory or database in codeigniter 4 app.

Image WaterMarking with Codeigniter 4 Example

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Connect App to Database
  • Create Controller Class
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to 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 and Table

Create database and table; so open your phpmyadmin and execute the following sql query on it to create table:

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 – Connect App to Database

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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,
	];

Step 5 – Create Controller Class

Create ImageUploadController.php file. So, visit app/Controllers directory and create 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('home');
   }
    
   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.');
        } 
   }


} ?>
  • The index() function renders image watermark template into the view.

Step 6 – Create Views

Create home.php view file, so visit app/views/ directory and create home.php file. Then add the following HTML into home.php file:

<!DOCTYPE html>
<html>

<head>
    <title>Codeigniter Adding Overlays Watermarks on Images Example - Laratutorials.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 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

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

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

Codeigniter 4 image watermarking example; In this tutorial,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 4 Tutorial

  1. Codeigniter 4 Ajax Form Submit Validation Example
  2. Codeigniter 4 File Upload Validation Example
  3. Image Upload with Validation in Codeigniter 4
  4. Codeigniter 4 Image Upload Preview Using jQuery Example
  5. Codeigniter 4 Ajax Image Upload Preview Example
  6. How to Upload Multiple Images in Codeigniter 4
  7. Codeigniter 4 Multiple Image Upload with Preview
  8. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  9. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  10. Codeigniter 4 CRUD with Datatables Example
  11. Codeigniter 4 Image Crop and Save using Croppie Example
  12. Dependent Dropdown using jQuery Ajax in Codeigniter 4
  13. CodeIgniter 4 Rest Api CRUD Example
  14. Codeigniter 4 Login Registration and Logout Example
  15. Get Address from Latitude and Longitude in Codeigniter 4
  16. Codeigniter 4 Google Column Charts Example
  17. Codeigniter 4 Google Place Autocomplete Address
  18. Export Data to Excel Example in Codeigniter 4
  19. Codeigniter 4 Google ReCaptcha V2 Example
  20. Codeigniter 4 Ajax Load More Data on Page Scroll
  21. Google Pie Chart in Codeigniter 4
  22. Codeigniter 4 Stripe Integration Example
  23. Codeigniter 4 Fullcalendar Integration Example
  24. Morris Bar Chart in Codeigniter 4
  25. Codeigniter 4 Morris Area and Line Chart Tutorial

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *