Introduction

This tutorial will show you how to upload and watermark image using Codeigniter. CodeIgniter’s File Uploading Class permits files to be uploaded. Codeigniter’s Image Library class allows us to process images, such as, crop, resize, rotate, watermark etc. You can set various preferences, restricting the type and size of the files.

So here we will upload the image first and then watermark the image. We will use here GD2 library for watermarking image. Here we will see example on text watermark.

Recommended Reading: Upload and Watermark(Overlay) Image using Codeigniter.

Types of Watermarking

There are two types of watermarking that you can use:

Text Watermarking

The watermark message will be generated using text, either with a True Type font that you specify, or using the native text output that the GD2 library supports. If you use the True Type version your GD2 installation must be compiled with True Type support (most are, but not all).

Overlay Watermarking

The watermark message will be generated by overlaying an image (usually a transparent PNG or GIF) containing your watermark over the source image.

Prerequisites

Apache 2.4, PHP 7.3.5, Codeigniter 3.1.10

How to enable GD2 library for PHP in Windows

Creating Project Directory

We need to first create our root project directory in order to implement the upload and watermark image using Codeigniter.

It’s assumed that you have setup Apache 2.4, PHP 7.3.5 and Codeigniter 3.1.10 in Windows system.

Next we will create a project root directory called codeIgniter-3.1.10-text-watermark-image under the Apache server’s htdocs folder.

Now move all the directories and files from Codeigniter 3.1.10 framework into  codeIgniter-3.1.10-text-watermark-image directory.

We may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project root directory.

Autoload Configuration

We need some configurations, such as, auto-loading for helpers to avoid loading every time we need to use.

$autoload['helper'] = array('html', 'url', 'file');

Creating Controller Class

Create a controller file ImageWatermark.php under application/controllers with the following source code.

The below controller class handles request and response for clients.

We define here method for performing upload and watermark operation.

The controller class has one method called index() that uploads the image, loads the GD2 & watermarks the image with the defined configurations in image_lib and sends to the view file.

We perform validations on input fields while uploading and watermarking image.

If you prefer not to set preferences using method $this->load->library('image_lib', $config), you can instead put them into a config file.

Simply create a new file called image_lib.php, add the $config array in that file. Then save the file in config/image_lib.php and it will be used automatically.

The below class uses default font from Operating System. If you want to use custom font then you can uncomment line $config['wm_font_path'] = APPPATH . 'ALGERIA.TTF'; to use this font or you may use different font.

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of ImageWatermark
 *
 * @author https://www.roytuts.com
 */
class ImageWatermark extends CI_Controller {

    //variable for storing error message
    private $error;
    //variable for storing success message
    private $success;

    function __construct() {
        parent::__construct();
        //load this to validate the inputs in upload form
        $this->load->library('form_validation');
    }

    //appends all error messages
    private function handle_error($err) {
        $this->error .= nl2br($err . "\n");
    }

    //appends all success messages
    private function handle_success($succ) {
        $this->success .= nl2br($succ . "\n");
    }

    public function index() {
        if ($this->input->post('image_watermark')) {
            //set preferences
            //file upload destination
            $upload_path = './upload/';
            $config['upload_path'] = $upload_path;
            //allowed file types. * means all types
            $config['allowed_types'] = 'jpg|png|gif';
            //allowed max file size. 0 means unlimited file size
            $config['max_size'] = '0';
            //max file name size
            $config['max_filename'] = '255';
            //whether file name should be encrypted or not
            $config['encrypt_name'] = TRUE;
            //store image info once uploaded
            $image_data = array();
            //check for errors
            $is_file_error = FALSE;
            //check if file was selected for upload
            if (!$_FILES) {
                $is_file_error = TRUE;
                $this->handle_error('Select an image file.');
            }
            //if file was selected then proceed to upload
            if (!$is_file_error) {
                //load the preferences
                $this->load->library('upload', $config);
                //check file successfully uploaded. 'image_name' is the name of the input
                if (!$this->upload->do_upload('image_name')) {
                    //if file upload failed then catch the errors
                    $this->handle_error($this->upload->display_errors());
                    $is_file_error = TRUE;
                } else {
                    //store the file info
                    $image_data = $this->upload->data();
                    $config['image_library'] = 'gd2'; //default value
                    $config['source_image'] = $image_data['full_path']; //get original image
                    $config['wm_text'] = 'Copyright 2019, roytuts.com';
                    $config['wm_type'] = 'text';
                    //$config['wm_font_path'] = APPPATH . 'ALGERIA.TTF';
                    //$config['wm_font_size'] = '18';
                    $config['wm_font_color'] = '#FF7433';
                    $config['wm_vrt_alignment'] = 'middle';
                    $config['wm_hor_alignment'] = 'left';
                    $config['wm_padding'] = '20';
                    $this->load->library('image_lib', $config);
                    if (!$this->image_lib->watermark()) {
                        $this->handle_error($this->image_lib->display_errors());
                    }
                }
            }
            // There were errors, we have to delete the uploaded image
            if ($is_file_error) {
                if ($image_data) {
                    $file = $upload_path . $image_data['file_name'];
                    if (file_exists($file)) {
                        unlink($file);
                    }
                }
            } else {
                $data['watermark_img'] = $upload_path . $image_data['file_name'];
                $this->handle_success('Image was successfully uploaded to direcoty <strong>' . $upload_path . '</strong> and watermarked.');
            }
        }

        //load the error and success messages
        $data['errors'] = $this->error;
        $data['success'] = $this->success;
        //load the view along with data
        $this->load->view('watermark-text', $data);
    }

}

Creating View Files

We will create few view files to perform our watermark operation on image.

Create a view file called watermark-text.php under application/views which will be used for uploading image and displaying the watermarked image.

This file defines a form for uploading image file and shows validations errors or success messages based on the criteria.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Codeigniter Image Watermark(Text)</title>
        <style type="text/css">

            ::selection { background-color: #E13300; color: white; }
            ::-moz-selection { background-color: #E13300; color: white; }

            body {
                background-color: #fff;
                margin: 40px;
                font: 13px/20px normal Helvetica, Arial, sans-serif;
                color: #4F5155;
            }            

            #body {
                margin: 0 15px 0 15px;
            }

            #container {
                margin: auto;
				width: 800px;
                border: 1px solid #D0D0D0;
                box-shadow: 0 0 8px #D0D0D0;
            }

            .error {
                color: #E13300;
            }

            .success {
                color: darkgreen;
            }
        </style>
    </head>
    <body>
        <div id="container">
            <h1>CodeIgniter Image Watermark(Text)</h1>

            <div id="body">
                <p>Select an image file to watermark</p>
                <?php
                if (isset($success) && strlen($success)) {
                    echo '<div class="success">';
                    echo '<p>' . $success . '</p>';
                    echo '</div>';
                }
                if (isset($errors) && strlen($errors)) {
                    echo '<div class="error">';
                    echo '<p>' . $errors . '</p>';
                    echo '</div>';
                }
                if (validation_errors()) {
                    echo validation_errors('<div class="error">', '</div>');
                }
                if (isset($watermark_img)) {
                    echo img($watermark_img);
                }
                ?>
                <?php
                $attributes = array('name' => 'image_upload_form', 'id' => 'image_upload_form');
                echo form_open_multipart($this->uri->uri_string(), $attributes);
                ?>
                <p><input name="image_name" id="image_name" readonly="readonly" type="file" /></p>
                <p><input name="image_watermark" value="Upload Image" type="submit" /></p>
                <?php
                echo form_close();
                ?>
            </div>

        </div>
    </body>
</html>

Configuring Route

Now modify application/config/routes.php file for pointing the default controller class.

$route['default_controller'] = 'imagewatermark';

Testing the Application

Home Page

Now if everything is fine run the application by hitting the URL http://[::1]/codeIgniter-3.1.10-text-watermark-image/index.php, you will see below output in the browser.

upload and watermark image using codeigniter

Uploaded and Watermarked Image

Now browse and select an image file, the file will be uploaded to application/upload directory with watermarked and the watermarked image will be displayed on browser.

Make sure upload directory exists under project root directory.

upload and watermarked using codeigniter

Source Code

You can download source code.

Thanks for reading.

Tags:

Leave a Reply

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