June 25, 2014

June 25, 2014
In this article, we are going to discuss about How to create an image gallery in CodeIgniter. CodeIgniter is quite mature framework to creating web application, the built in libraries and helper very helpful to creating most feature in web application. This article is describes about How to create a very basic image gallery using CodeIgniter, the built in libraries that I used are File Uploading, Image Manipulation and Pagination, whereas the used helper is URL Helper.

Step 1:

Open the "config.php" file which is in the folder "system/application/config/" and set the CodeIgniter base_url

$config['base_url'] = "http://localhost/ci_gallery/";

Step 2:

Load the URL Helper in "autoload.php" file which is in the same folder as above file

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

Step 3:

Create an image controller in file "image.php" which is in the folder "system/application/controller" and add the below attribute inside the image class

private $data = array(
    'dir' => array(
        'original' => 'assets/uploads/original/',
        'thumb' => 'assets/uploads/thumbs/'
    ),
    'total' => 0,
    'images' => array(),
    'error' => ''
);

Step 4:

The variable which is created in the above file is to store the default directory path, total images inside the folder, and error message while uploading the image, the value of those variables will set in the next function.

Add the function index inside the Image class

public function index($start = 0)
{
    if ($this->input->post('btn_upload')) {
        $this->upload();
    }

    $this->load->library('pagination');

    $c_paginate['base_url'] = site_url('image/index');
    $c_paginate['per_page'] = '9';
    $finish = $start + $c_paginate['per_page'];

    if (is_dir($this->data['dir']['thumb']))
    {
        $i = 0;
        if ($dh = opendir($this->data['dir']['thumb'])) {
            while (($file = readdir($dh)) !== false) {
                // get file extension
                $ext = strrev(strstr(strrev($file), ".", TRUE));
                if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png') {
                    if ($start <= $this->data['total'] && $this->data['total'] < $finish) {
                        $this->data['images'][$i]['thumb'] = $file;
                        $this->data['images'][$i]['original'] = str_replace('thumb_', '', $file);
                        $i++;
                    }
                    $this->data['total']++;
                }
            }
            closedir($dh);
        }
    }

    $c_paginate['total_rows'] = $this->data['total'];

    $this->pagination->initialize($c_paginate);

    $this->load->view('images/index', $this->data);
}

Inside the index function it will call the upload function when the upload button is clicked by the user, and the pagination class is configured, the script is looping through the folder find whether the file is image or not, and now the upload function.

private function upload()
{
    $c_upload['upload_path']    = $this->data['dir']['original'];
    $c_upload['allowed_types']  = 'gif|jpg|png|jpeg|x-png';
    $c_upload['max_size']       = '500';
    $c_upload['max_width']      = '1600';
    $c_upload['max_height']     = '1200';
    $c_upload['remove_spaces']  = TRUE;

    $this->load->library('upload', $c_upload);

    if ($this->upload->do_upload()) {

        $img = $this->upload->data();

        // create thumbnail
        $new_image = $this->data['dir']['thumb'].'thumb_'.$img['file_name'];

        $c_img_lib = array(
            'image_library'     => 'gd2',
            'source_image'      => $img['full_path'],
            'maintain_ratio'    => TRUE,
            'width'             => 100,
            'height'            => 100,
            'new_image'         => $new_image
        );

        $this->load->library('image_lib', $c_img_lib);
        $this->image_lib->resize();
    } else {
        $this->data['error'] = $this->upload->display_errors();
    }
}

You can see on the code above, thumbnail is created every time image is uploaded to maximum size 100 x 100 pixels, and putted in the different folder , the last function is delete image

public function delete($ori_img)
{
    unlink($this->data['dir']['original'].$ori_img);
    unlink($this->data['dir']['thumb'].'thumb_'.$ori_img);
    redirect('/');
}

The function getting the parameter as image name and deleted the orginal and thumbnail image, and now the view file "index.php" which is in the folder "system/application/views/images/"

<!-- the javascript code to load clicked image and changing the class-->
<script type="text/javascript">
    function changepic(img_src, obj) {
        document["img_tag"].src = img_src;
        var thumbs = document.getElementsByName("thumb");
        for (var i = 0; i < thumbs.length; i++) {
            var tmp_id = "thumb_" + i;
            document.getElementById(tmp_id).setAttribute("class", "thumb");
        }
        document.getElementById(obj).setAttribute("class", "thumbclick");
        var ori_img = img_src.replace("thumb_", "");
        document.getElementById("detimglink").setAttribute("href", ori_img);
    }
</script>

<!-- the view file -->
<div id="container">
    <div id="imgshow">
        <?php if (isset($images[0])) { ?>
        <a href="<?php echo base_url().$dir['original'].$images[0]['original']; ?>" target="_blank" id="detimglink">
            <img class="imgdet" name="img_tag" src="<?php echo base_url().$dir['original'].$images[0]['original']; ?>" width="500"/>
        </a>
        <?php } ?>
    </div>

    <div id="imglist">
        <form enctype="multipart/form-data" id="fupload" method="post" action="<?php echo site_url('image/'); ?>">
            <input name="userfile" type="file" size="20"/>
            <input type="submit" name="btn_upload" value="Upload &uarr;" class="btnupload"/>
            <?php if (isset ($error)) { ?>
            <div class="error"><?php echo $error; ?></div>
            <?php } ?>
        </form>

        <div class="clear"></div>

        <div class="imgfor">
        <!-- Looping Array Image -->
        <?php foreach($images as $key => $img) { ?>
        <div class="imgbox">
            <div>
                <a href="javascript:" onclick="changepic('<?php echo base_url().$dir['original'].$img['original']; ?>', 'thumb_<?php echo $key; ?>');">
                <img class="thumb" name="thumb" id="thumb_<?php echo $key; ?>" src="<?php echo base_url().$dir['thumb'].$img['thumb']; ?>"/>
                </a>
            </div>
            <div class="dadel">
            <a class="adel" href="<?php echo site_url('image/delete/'.$img['original']); ?>">
                delete
            </a>
            </div>
        </div>
        <?php } ?>
        <div class="clear"></div>
        </div>
        <div class="clear"></div>

        <div class="bottom">
            <?php echo $total; ?> Image(s)
        </div>

        <div class="bottom">
            <?php echo $this->pagination->create_links(); ?>
        </div>
    </div>

    <div class="clear"></div>

</div> <!-- end div container -->

0 comments:

Post a Comment