How to watermark images using codeigniter php framework

How to watermark images using codeigniter

Codeigniter is very popular MVC php framework. Images can be processed very easily in codeigniter. In previous tutorials we discussed basics of GD library in php and codeigniter file upload. But if you need to upload and manipulate images like crop, rotate, resize or watermark images using codeigniter, this article explains in detail.

In order to do this codeigniter provide a great image manipulation library, to perform all of above tasks. In this article you will learn how to:

1. Resize an image

2. Create thumbnail of an image

3. Crop an image

4. Rotate an image

5. Watermark images using codeigniter

Upload and manipulate image using image library in codeigniter

To demonstrate how to watermark images using codeigniter, first step is to upload an image to server and then resize, create a thumbnail, crop, rotate or watermark. Image upload is already discussed in detail in  codeigniter file upload tutorial. Here in this tutorial same code for view and controller is used to upload image. To use codeigniter image library we need to initialize it first.


Consequently after loading library, its object is available to use and we can use image library methods.


Create a codeigniter project in web root folder

Download and unzip codeigniter. Copy codeigniter to root folder of your MAMP, XAMPP or WAMP installation, rename this folder as ciwatermark. Codeigniter is MVC or Model, View, Controller php framework. Consequently you have to create a controller and view file to upload and watermark images using codeigniter.

Project folder structure of ciwatermark

project folder - watermark images using codeigniter

Adding a codeigniter view file

In addition to add a view file first open application folder, then views folder and add php file named image.php. Add following code in view file.


defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>



<title>Crop, rotate, resize and watermark images using codeigniter</title>



<?php echo $error; ?>

<h3>Upload and watermark images using codeigniter</h3>

<p style='text-align: center'>

<?php echo form_open_multipart('image/upload_file'); ?>

<input type="file" name="userimage" size="20" />

<br /><br />

<input type="submit" value="Upload Image" />





A form is added using codeigniter‘s form library. Form library has a function


This function creates HTML form with enctype=”multipart/form-data” attribute used when an image or a file is uploaded to server.

HTML form in view file

codeigniter form - upload and watermark images using codeigniter

Create directory for uploading and saving files

Open main directory of project named ciwatermark. Create a directory named files in it. We are going to save uploaded images in this directory.

Adding a codeigniter controller file

Open controller folder and add a file named Image.php. Initialize it with following code.

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

  class Image extends CI_Controller {
        public function __construct()
            $this->load->helper(array('form', 'url'));
            $this->load->library('form_validation', 'image_lib');

        public function index()
          $this->load->view('image', array('error' => ' ' ));
        public function upload_file()
                $config['upload_path']          = './files/';
                $config['allowed_types']        = 'gif|jpg|jpeg|png';

                $config['max_size']             = 500;

                $config['max_width']            = 1024;

                $config['max_height']           = 768;
                $this->load->library('upload', $config);

                if ( ! $this->upload->do_upload('userimage'))
                    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
                    $error = array('error' => $this->upload->display_errors());

                    $this->load->view('image', $error);
                    $data = array('upload_data' => $this->upload->data());
                    $file_name = $data['upload_data']['file_name'];

                    /* Image resize, crop, rotate, watermark code here */

                    $this->load->view('success', $data); 


Above code is discussed in detail in codeigniter file upload example tutorial. It has a class Image that extends CI_Controller class. In constructor of class required libraries and helpers are loaded. Index function loads view image and displays the form.

Moreover upload_file function receives user image and validates it for allowed types, max_size, max_width and height. After data validation file is uploaded to server in specified folder and success view page is loaded. Moreover you are going to add the further image manipulation code after upload.

Image manipulation using codeigniter

We can resize, crop, create thumbnail or watermark images using codeigniter image library. Whatever processing you are going to perform on an image, there are some configuration parameters or preferences that need to be set. These preferences include image library, source image, height, width and others.

To resize, crop, create thumbnail or watermark images using codeigniter image library methods we have to:

1. Set basic preferences or config parameters.

2. Load image_lib library and pass preferences

3. Call required method(resize, crop, create thumbnail or watermark) of image library object

Sample Image used:

sample image - resize crop rotate watermark images using codeigniter

Resize an image using codeigniter image library

To resize an image add following code in controller image.php‘s upload_file method in else  block under these code lines.

$data = array('upload_data' => $this->upload->data());

$file_name = $data['upload_data']['file_name'];

codeigniter resize image code

Code below resizes an image.

$imgConfig = array();

$imgConfig['image_library']    = 'gd2';
$imgConfig['source_image']     = './files/'.$file_name;
$imgConfig['create_thumb']     = FALSE;
$imgConfig['maintain_ratio']   = TRUE;
$imgConfig['width']            = 150;
$imgConfig['height']           = 75;   

$this->load->library('image_lib', $imgConfig);
if (!$this->image_lib->resize()){
    echo $this->image_lib->display_errors();

In the code image configuration array is initialized and basic preferences are set.

1. image_library      – GD2 is initialized as image library

2. source_image     – Image that is going to be resized, this is image that user will upload.

3. create_thumb     – Whether to create thumb or not, set to FALSE

4. maintain_ration –  Whether to maintain aspect ratio of original image. Set to Yes

5. width, height       – width, height is defined and  set to 150 , 75 respectively.

new_image attribute can also be specified to create copy of image with path an name.

create_thumb attribute when set to true,  thumbnail of image is created.

Further  image_lib is loaded, basic configuration array is passed to function.

$this->load->library('image_lib', $imgConfig);

After library is loaded, image_lib‘s resize method is called in an if condition. If resize method returns false then display_errors() method of image_lib library displays errors.

if (!$this->image_lib->resize()){
    echo $this->image_lib->display_errors();

Resized image:

The image below is resized with codeigniter image_lib library.

resized_image - resize watermark images using codeigniter

Generate thumbnail of an image using codeigniter

Resize method can be used to create thumbnails as well, If  we set create_thumb parameter to TRUE, thumbnail of image is generated.


Original image remains preserved and a thumbnail is created and saved with specified name and path. Thumbnail is saved with originalfilename_thumb.ext name. _thumb is added after original image name.

Create copy of an image using codeigniter

image_lib library’s resize method can also be used to create copy of original image. The parameter that need to provide is $config[‘new_image’] = ‘/path/to/new_image.jpg’;.

new_image create a copy of image and saves in in same folder or specified path. If we only specify new image name it will be saved in same directory, if path is specified new image will be saved in new path with same name, If path and new name both are specified, image will be saved on specified path with new name.

Crop an image using codeigniter

To crop and image using image_lib, we need to set some basic preferences. Before cropping a picture we need to understand the difference between resizing an image and cropping an image.

Difference between resizing an image and cropping an image in codeigniter

Resizing an image and cropping an image in codeigniter are almost same. Difference is that in crop() method we need to provide x-axis and y-axis with height and width.

X-coordinate  specifies the X-coordinate for cropping of image. Suppose x-axis is set as 100.  So crop() method will crop image 100 pixels from left side. Setting y-coordinate to 75 will start cropping 75 pixel from top position of image.

codeigniter crop image code

$imgConfig = array();
$imgConfig['image_library']= 'gd2';

$imgConfig['source_image'] = './files/'.$file_name;
$imgConfig['new_image']    = './files/crop_'.$file_name;
$imgConfig['height'] = '300';
$imgConfig['width']  = '200';
$imgConfig['x_axis'] = '150';
$imgConfig['y_axis'] = '150';
$this->load->library('image_lib', $imgConfig);

if ( ! $this->image_lib->crop()){
    echo $this->image_lib->display_errors();

Code explanation

Hence the code above crops the image according to the specifications. $imgConfig is initialize  and basic parameters are set. As before GD2 as image_library, Source image is uploaded to files directory.

$imgConfig['new_image']    = './files/crop_'.$file_name;

new_image parameter tells image library that create a copy of the original image with specified height & width and name it as crop_original_file_name.jpg. As you can see crop_ is prefixed with original image name. So original and cropped images are uploaded and copied to same directory.

Moreover after specifying height and width  for cropped image, two new parameters are added as x-axis , y-axis.

$imgConfig['x_axis'] = '150';
$imgConfig['y_axis'] = '150';

x-axis value is 150  and y-axis is also specified as 150px so image cropping starts from 150px from left and 150px from top. Next after loading and initializing the image_lib with $imgConfig config array crop function is called. On success original image is cropped otherwise error is shown.

Cropped image:

You can see that image is cropped from 150px x-axis and y-axis with height and width 300 X 200.

cropped_sample_image watermark images using codeigniter

Rotate an image using codeigniter image library

For rotating an image we have to provide rotation_angle parameter with other configurations. rotation_angle  parameter can have 5 values.

1. 90 degree – Image is rotated 90 degrees clock wise direction.

2. 180 degree – Image is rotated 180 degrees clock wise direction.

3. 270 degree – Image is rotated 270 degrees clock wise direction.

4. hor – image is flipped horizontally.

5. vrt – image is flipped vertically

Codeigniter rotate image code

$imgConfig = array();
$imgConfig['image_library']  = 'gd2';
$imgConfig['source_image']   = './files/'.$file_name;
$imgConfig['height'] = '400';
$imgConfig['width']  = '400';
$imgConfig['rotation_angle'] = '90';
$imgConfig['new_image']      = './files/rot_'.$file_name;
$this->load->library('image_lib', $imgConfig);
if ( ! $this->image_lib->rotate()){
      echo $this->image_lib->display_errors();                      

A new parameter is rotation_angle.

$imgConfig['rotation_angle'] = '90';

This parameter rotates the image 90 degrees clockwise. rot is also prefixed before original image name. Rotated image can be seen below.

rotated_sample_image_watermark images using codeigniter

Watermark images using codeigniter image library

There are two types of watermarking. Text and overlay using GD or GD2 library.

1. Text: You have to specify a text and text is used as a watermark message.

2. Overlay: You can use a transparent PNG or GIF image, that will serve as a watermark over the uploaded source image.

Text watermark images using codeigniter

To watermark images using codeigniter first we set basic configuration parameters.

$imgConfig = array();
$imgConfig['image_library']   = 'GD2';
$imgConfig['source_image']    = './files/'.$file_name;
$imgConfig['wm_text']         = 'Copyright 2016 - Programmer Blog';
$imgConfig['wm_type']         = 'text';
$imgConfig['wm_font_size']    = '16';
$this->load->library('image_lib', $imgConfig);
$this->load->view('success', $data);

As in other functions, some basic configuration parameters are set here,  After defining image_library and source image, we define wm_text as watermark text, watermark type as wm_type and font as  wm_font_size.

After loading and initializing image library’s watermark() method is called. Image with text watermark is created.

sample image - watermark images using codeigniter

Overlay watermark  images using codeigniter

Text watermark type uses text to watermark images but in overlay watermark a GIF or PNG image is used as watermark symbol over source image.

$imgConfig = array();
$imgConfig['image_library'] = 'GD2';
$imgConfig['source_image']  = './files/'.$file_name;

$imgConfig['wm_type']       = 'overlay';    
$imgConfig['wm_overlay_path'] = './files/overlay_programmerblog.png';
$this->load->library('image_lib', $imgConfig);

After basic preferences we set watermark type as overlay and watermark overlay image path that is Programmer Blog‘s logo. After loading and initializing the image_lib library we pass configuration parameters and call watermark() function. In the image below you can see PB logo is watermarked on image.

overlay watermark images using codeigniter


Source code for resize, crop, rotate and watermark images using codeigniter

Finally Click Here to download complete source code to watermark images using codeigniter. Unzip this code in www or root folder of your XAMPP, WAMP or LAMP installation. Further open browser and type following URL http://localhost/ciwatermark/index.php/image.


To summarize in this tutorial you have learnt how to crop, rotate, resize and watermark images using codeigniter image library. With this in mind please leave your valuable feedback and comments. Stay tuned for upcoming great tutorials.

About Jason William