Upload image and thumbnail generation in Code Igniter

Controller

  function index()
  {
    $this->load->model('Gallery_model');

    if($this->input->post('upload')){
      $this->Gallery_model->do_upload();
    }

    $this->load->view('gallery');

  }

view

    <?php 

      echo form_open_multipart('gallery');
      echo form_upload('userfile'); //userfile is default... dont bother changing
      echo form_submit('upload', 'Upload bebs!');
      echo form_close();
    ?>
class Gallery_model extends Model {

  var $gallery_path;
  var $gallery_path_url;

  function Gallery_model()
  {
    parent::Model(); // a must for constructor

    //APPPATH IS AVAILABLE IN THE ENTIRE CODEIG
    $this->gallery_path = realpath(APPPATH . '../images');
    $this->gallery_path_url = base_url().'images/'; //dunno for what
  }

  function do_upload()
  {
    $config = array(
      'allowed_types' => "jpg|jpeg|gif|png",
      'upload_path' => $this->gallery_path,
      'max_size'=>2000
    );
    $this->load->library('upload', $config);
    $this->upload->do_upload(); //do upload

    //want to create thumbnail

    $image_data = $this->upload->data(); //get image data

    $config = array(
      'source_image' => $image_data['full_path'], //get original image
      'new_image' => $this->gallery_path . '/thumbs', //save as new image //need to create thumbs first
      'maintain_ratio' => true,
      'width' => 150,
      'height' => 100

    );

    $this->load->library('image_lib', $config); //load library
    $this->image_lib->resize(); //do whatever specified in config
  }

}

Related posts:

  1. Pagination in Code Igniter
  2. Validation in Code Igniter
  3. CodeIgniter Controller for Sending Email via Gmail SMTP
  4. Ways to Retrieve Data from MySQL Database Using CodeIgniter
  5. Increase Max Upload Size on WordPress
  1. trdouglas says:

    This is interesting to me because I am just learning CI and have started playing with image upload and manipulation.

    If I want to insert the resulting image path into a db, is this how I would proceed…

    In the Gallery controller, after “do_upload” check if the upload was a success. Then the Gallery controller would call another function in the Gallery_model to insert $image_data in the db.

    Does that sound correct?

  2. Aditya says:

    sounds better. error checking is definitely a plus. may I know how you do that?

  3. Steve says:

    I’ve been watching the CodeIgniter from Scratch series on NetTuts+, and in digging a bit deeper into image manipulation I came across this page, which seems to be an excerpt from the episode I just finished watching. Check it out for more info – CodeIgniter – File Uploading and Image Manipulation

  1. There are no trackbacks for this post yet.

Leave a Reply