Basic Image Gallery With CodeIgniter

June 27th, 2010 by aditia rahman / 28 Comments  

     

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 post I want to create very basic image gallery using CodeIgniter, the the built in libraries that I used are File Uploading, Image Manipulation and Pagination, whereas the used helper is URL Helper, and here’s we go

First open the config.php in folder system/application/config/ and set the CodeIgniter base_url

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

Next load the URL Helper in autoload.php in the same folder as above file

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

Now create the image controller in file image.php inside folder system/application/controller and add this attribute inside the image class

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

The varible above created 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 called the upload function when upload button 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 inside 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 -->

The result is like the image below, i’m not posting the css code in here but you can see on the demo (sorry, the upload and delete feature disabled) or the downloadable source code, and the code included some sample image so the size is bigger than fresh copy CodeIgniter.

DOWNLOAD SOURCE | DEMO

in case the download link above not working try this:

http://www.box.net/shared/h1405cfukr or http://min.us/mveQ86i

        submit to reddit Delicious

Others You May Like

28 Comments Leave a Comment Subscribe RSS

Leave a Comment