Monday, December 19, 2016

CodeIgniter Image Watermark

CodeIgniter Image Manipulation class lets us resize image, create thumbnail, crop, rotate and watermark images.
This tutorial shows a simple way to upload and watermark an image. Watermarking is only available using the GD/GD2 library.In addition, even though other libraries are supported, GD is required in order for the script to calculate the image properties. The image processing, however, will be performed with the library you specify.

At the end of this tutorial, you would be able to watermark images similar to the following images.
Overlay

Text

Two Types of Watermarking

We could either use text or image to watermark our image.
1. Text: The watermark will be generated using text, either with a True Type font that you specify, or using the native text output that the GD library supports.
2. Overlay: The watermark message will be generated by overlaying an image (usually a transparent PNG or GIF) containing your watermark over the source image.

Step 1.Create a controller

Create a controller by pasting the following code and name it as "Upload.php"
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Upload extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        $this->load->view('upload');
    }
}
The index function simply loads "upload" view which we'll be creating on the next step.

Step 2. Create a view

We need to create a view which is basically our html file.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Contact Form Example</title>
    <!--load bootstrap css-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous">

    <style>
        .container{
            padding:5%;
        }
        .modal .modal-body{
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 57px 0px 57px 0px;
        }
        .modal .modal-title{
            text-align:center;
        }
        .custom-file-control{
            overflow:hidden;
            position: absolute;
            top: 0;
            right: 0;
            left: 0;
            z-index: 5;
            height: 2.5rem;
            padding: .5rem 1rem;
            line-height: 1.5;
            color: #555;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: .25rem;
        }
        .custom-file-control::before{
            content:"Browse";
            position: absolute;
            top: -1px;
            right: -1px;
            bottom: -1px;
            z-index: 6;
            display: block;
            height: 2.5rem;
            padding: .5rem 1rem;
            line-height: 1.5;
            color: #555;
            background-color: #eee;
            border: 1px solid #ddd;
            border-radius: 0 .25rem .25rem 0;
        }
        .custom-file-control::after{
            content:attr(data-attr);
        }
        .flex-center-cont{
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        #img-prev-cont{
            text-align:center;
            width:100%;
            height:150px;
            overflow: hidden;
            background-color:#ccc;
            border: 2px dashed #a6afa7;
            line-height: 150px;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>var base_url = "<?=base_url();?>";</script>
</head>
<body>
    <div class="container">
        <div class="row flex-items-xs-center flex-center-cont">
            <div class="col-xs-4">
                <form action="#" id="upload-form">
                    <div id="img-prev-cont" class="form-group">
                        <img src="https://placehold.it/190x150" alt="Image Preview" id="img-prev" class="img-fluid">
                    </div>
                    <div class="form-group">
                        <label class="custom-file col-xs-12">
                            <input type="file" id="file" class="custom-file-input" name="myfile" placeholder="Choose file">
                            <span class="custom-file-control" data-attr="Choose file..."></span>
                        </label>
                    </div>
                    <div class="form-group">
                        <select name="watermark_type" class="form-control">
                            <option value="text">Text</option>
                            <option value="overlay">Image Overlay</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <input name="submit" type="submit" class="btn btn-lg btn-outline-success btn-block" value="Submit" />
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="https://www.atlasestateagents.co.uk/javascript/tether.min.js"></script><!-- Tether for Bootstrap -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js" integrity="sha384-BLiI7JTZm+JWlgKa0M0kGRpJbF2J8q+qreVrKBC47e3K6BW78kGLrCkeRX6I9RoK" crossorigin="anonymous"></script>
    <script>
        $(function(){
            $('input[name="myfile"]').on('change',function(e){
                var filename = document.getElementById("file").files[0].name;
                $(this).next().attr('data-attr',filename);
                $('input[name="myfile"]').closest('.form-group.has-error').removeClass('has-error').find('span.text-danger').remove();
                readURL(this);
            })
            function readURL(input) {
                if (input.files && input.files[0]) {
                    var file = input.files[0];
                    var fileType = file["type"];
                    var ValidImageTypes = ["image/gif", "image/jpeg", "image/png"];
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        if ($.inArray(fileType, ValidImageTypes) > 0) {
                            $('#img-prev').attr('src', e.target.result);
                        }
                        else{
                        }
                    }
                    reader.readAsDataURL(input.files[0]);
                }
            }
            $('#upload-form').on('submit',function(e){
                e.preventDefault();
                var $btn = $(this).find('input[type="submit"]');
                var formdata = new FormData(this);
                $.ajax({
                    url: base_url+'upload/do_upload',
                    type: 'POST',
                    dataType: 'JSON',
                    data:formdata,
                    cache:false,
                    contentType: false,
                    processData: false,
                    beforeSend:function(){
                        $btn.button('loading');
                    },
                    success:function(response){
                        $('.form-group.has-error').removeClass('has-error').find('span.text-danger').remove();
                        switch(response.status){
                            case 'form-incomplete':
                                $.each(response.errors, function(key,val){
                                    if(val.error!=''){
                                        $(val.field).closest('.form-group').addClass('has-error').append(val.error);
                                    }
                                })
                            break;
                            case 'success':
                                // window.location.reload(true);
                                var data = 
                                    "<div class='col-xs'>"+
                                        "<div class='text-center'>Watermarked Image</div>"+
                                        "<img src='"+base_url+'uploads/files/img/'+response.data.file_name+"'>"+
                                        "<table class='table'>"+
                                             "<thead class='thead-inverse'>"+
                                                "<tr>"+
                                                    "<th>"+
                                                        "Key"+
                                                    "</th>"+
                                                    "<th>"+
                                                        "Value"+
                                                    "</th>"+
                                                "</tr>"+
                                             "</thead>";
                                $.each(response.data,function(key,val){
                                    data+=
                                    "<tr>"+
                                        "<td>"+
                                            key+
                                        "</td>"+
                                        "<td>"+
                                            val+
                                        "</td>"+
                                    "<tr>";
                                })
                                data+="</table></div>";
                                $(".flex-center-cont").append(data);
                            break;
                            case 'error':
                                $('input[name="myfile"]').closest('.form-group').addClass('has-error').append("<span class='text-danger'>"+response.errors+"</span>");
                                console.log(response.message);
                            break;
                        }
                    },
                    error: function(jqXHR,textStatus,error){
                        console.log('Unable to send request!');
                    }
                }).always(function(){
                    $btn.button('reset');
                });
            })
        })
    </script>
</body>
</html>
This is a simple view which has a form that allows us to upload an image and specify which watermark we want to use.
We're not quite done yet, we need to create "do_upload" function on our "Upload" controller which we specified on our Ajax url.

Step 3. Watermark

Go ahead and createa a "do_upload" function on "Upload" Controller.
public function do_upload()
    {
        if(!$this->input->is_ajax_request()){
            show_404();
        }
        try{
            if( ! empty($_FILES['myfile']))
            {
                $watermark_type = $this->input->post('watermark_type');
                $config=  array(
                    'upload_path'      => "./uploads/files/img/",
                    'allowed_types'   => "gif|jpg|png|jpeg",
                    'overwrite'       => TRUE,
                    'max_size'        => "1000KB",
                    'max_height'      => "768",
                    'max_width'       => "1024"  
                );
                if(!is_dir($config['upload_path'])){
                    mkdir($config['upload_path'], 0777, TRUE);
                }
                
                $this->load->library('upload', $config);
                $response = false;
                if($this->upload->do_upload('myfile'))
                {
                    $response['status'] = 'success';
                    $response['message'] = 'Successfully uploaded';
                    $response['data'] = $this->upload->data();

                    //Watermark newly uploaded image
                    $this->load->library('image_lib');
                    $config['source_image'] = './uploads/files/img/'.$response['data']['file_name'];
                    
                    if($watermark_type == 'text'){
                        $config['wm_text'] = 'kodemadesimple.com';
                        $config['wm_type'] = 'text';
                        $config['wm_font_path'] = './assets/fonts/trench100free.ttf';
                        $config['wm_font_size'] = 16;
                        $config['wm_font_color'] = 'ffffff';
                        $config['wm_padding'] = '20';
                    }
                    else if($watermark_type == 'overlay'){
                        $config['image_library'] = 'gd2';
                        $config['wm_type'] = 'overlay';
                        $config['wm_overlay_path'] = './uploads/files/img/overlay.png';//the overlay image
                        $config['wm_x_transp'] = 4;
                        $config['wm_y_transp'] = 4;
                        $config['width'] = 50;
                        $config['height'] = 50;
                        $config['padding'] = 50;
                        $config['wm_opacity'] = 40;
                    }
                    $config['wm_vrt_alignment'] = 'middle';
                    $config['wm_hor_alignment'] = 'center';

                    $this->image_lib->initialize($config);
                    if (!$this->image_lib->watermark()) {
                        $response['wm_errors'] = $this->image_lib->display_errors();
                        $response['wm_status'] = 'error';
                    } else {
                        $response['wm_status'] = 'success';
                    }
                }
                else
                {
                    $response['status'] = 'error';
                    $response['message'] = 'Failed to upload file';
                    $response['errors'] = $this->upload->display_errors();
                }
            }
            else{
                $response['status'] = 'error';
                $response['message'] = 'Please select an image to upload';
            }
        }
        catch(Exception $e){
            $response['status']='error';
            $response['message']='Something went wrong while trying to communicate with the server.';
        }
        echo json_encode($response);
    }
What this function does is it first checks if it has been requested through ajax. If it isn't, it throws a 404 page, otherwise it validates the file with the preferences we've set up. It is then watermarked after it has been successfully uploaded.
If you wish to know more options which you could use click here.

8 comments:

  1. Photo Watermark does exactly what the name suggests – it lets you add watermarks to photos – but the types of watermarks you can add are quite varied.
    Not only can you add custom text as a watermark (including changing the font, size and color), you can also use your signature (or any other hand-written text) as a watermark by writing on the screen.
    You can also apply stickers, a timestamp, a location, a mosaic effect, or ‘graffiti’ (which basically just lets you go wild on your images with a digital paintbrush). Whether you want to protect your photo or just log when and where it was taken, there should be a tool here to suit.
    Photo Watermark is free, but it’s quite heavy on adverts. For $0.99/£0.89 per month you can get rid of them, but unless you’re adding watermarks to a ton of images it’s probably not worth it.

    ReplyDelete
    Replies
    1. Hello World !
      Good Day !

      Keep you services updated & reliable with my stuff
      Huge stuff of Tools, E-boooks, Tutorials, Scripting, Viruses, Spying e.t.c

      See Me On
      I C Q :> 752822040
      Tele-Gram :> @killhacks

      Many other stuff like
      SSN/DL
      ID's
      CC CVV
      DUMPS
      Combos/I.P's/Proxies
      You can get from my collections :-)

      No one TEACH you
      No one GUIDE you
      No one BOOST you
      But I'm always here for you

      Hit me up for you desired stuff
      I C Q here :> 752822040
      Tele-Gram here :> @killhacks

      %Waiting for you guys%

      Delete
  2. Photo Watermark does exactly what the name suggests – it lets you add watermarks to photos – but the types of watermarks you can add are quite varied.
    Not only can you add custom text as a watermark (including changing the font, size and color), you can also use your signature (or any other hand-written text) as a watermark by writing on the screen.
    You can also apply stickers, a timestamp, a location, a mosaic effect, or ‘graffiti’ (which basically just lets you go wild on your images with a digital paintbrush). Whether you want to protect your photo or just log when and where it was taken, there should be a tool here to suit.
    Photo Watermark is free, but it’s quite heavy on adverts. For $0.99/£0.89 per month you can get rid of them, but unless you’re adding watermarks to a ton of images it’s probably not worth it.

    ReplyDelete
  3. Photo Watermark does exactly what the name suggests – it lets you add watermarks to photos – but the types of watermarks you can add are quite varied.
    Not only can you add custom text as a watermark (including changing the font, size and color), you can also use your signature (or any other hand-written text) as a watermark by writing on the screen.
    You can also apply stickers, a timestamp, a location, a mosaic effect, or ‘graffiti’ (which basically just lets you go wild on your images with a digital paintbrush). Whether you want to protect your photo or just log when and where it was taken, there should be a tool here to suit.
    Photo Watermark is free, but it’s quite heavy on adverts. For $0.99/£0.89 per month you can get rid of them, but unless you’re adding watermarks to a ton of images it’s probably not worth it.

    ReplyDelete
  4. Photo Watermark does exactly what the name suggests – it lets you add watermarks to photos – but the types of watermarks you can add are quite varied.
    Not only can you add custom text as a watermark (including changing the font, size and color), you can also use your signature (or any other hand-written text) as a watermark by writing on the screen.
    You can also apply stickers, a timestamp, a location, a mosaic effect, or ‘graffiti’ (which basically just lets you go wild on your images with a digital paintbrush). Whether you want to protect your photo or just log when and where it was taken, there should be a tool here to suit.
    Photo Watermark is free, but it’s quite heavy on adverts. For $0.99/£0.89 per month you can get rid of them, but unless you’re adding watermarks to a ton of images it’s probably not worth it.

    ReplyDelete
  5. Photo Watermark does exactly what the name suggests – it lets you add watermarks to photos – but the types of watermarks you can add are quite varied.
    Not only can you add custom text as a watermark (including changing the font, size and color), you can also use your signature (or any other hand-written text) as a watermark by writing on the screen.
    You can also apply stickers, a timestamp, a location, a mosaic effect, or ‘graffiti’ (which basically just lets you go wild on your images with a digital paintbrush). Whether you want to protect your photo or just log when and where it was taken, there should be a tool here to suit.
    Photo Watermark is free, but it’s quite heavy on adverts. For $0.99/£0.89 per month you can get rid of them, but unless you’re adding watermarks to a ton of images it’s probably not worth it.

    ReplyDelete
  6. Hello World !
    Good Day !

    Keep you services updated & reliable with my stuff
    Huge stuff of Tools, E-boooks, Tutorials, Scripting, Viruses, Spying e.t.c

    See Me On
    I C Q :> 752822040
    Tele-Gram :> @killhacks

    Many other stuff like
    SSN/DL
    ID's
    CC CVV
    DUMPS
    Combos/I.P's/Proxies
    You can get from my collections :-)

    No one TEACH you
    No one GUIDE you
    No one BOOST you
    But I'm always here for you

    Hit me up for you desired stuff
    I C Q here :> 752822040
    Tele-Gram here :> @killhacks

    %Waiting for you guys%

    ReplyDelete