PinoyTech.org

CodeIgniter, Kohana, Mootools, jQuery and CSS

CodeIgniter Image Manipulation Class: How to Resize

Posted by teejay on December 1, 2009

CodeIgniter logo

The CodeIgniter Image Manipulation Class is a useful tool when implementing simple resize, cropping, rotate, watermarking and flipping of images are required in your project.

Here is a series of code templates for using the CodeIgniter Image Manipulation Class:

First one is resizing:

HTML

<form action="http://pinoytech.org/projects/image_editor/image/edit_image/" method="post">

 <input type="hidden" name="image" value="dsc01060.jpg" />
 <?php echo $this->session->flashdata('message');?>
 <?php echo isset($errors) ? $errors : '' ;?>

 <label class="label">Width</label> 
 <input type="text" name="width" class="text_field" /> 
 <span class="description">desired width in pixels</span> 

 <label class="label">Height</label> 
 <input type="text" name="height" class="text_field" /> 
 <span class="description">desired height in pixels</span> 

 <label class="label">Options</label> 
 <div> 
  <input type="checkbox" name="ratio" id="radio_1" class="checkbox" value="true" /> <label for="radio_1" class="radio">Maintain Ratio</label> 
 </div> 
 <div class="group navform"> 
  <input type="submit" class="button" name="resize" value="Resize Image" /> 
 </div> 
</form>

PHP

function edit_image()
{
 $this->load->helper(array('form', 'html'));

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

 if($this->input->post('resize') AND $this->form_validation->run('resize_image') === TRUE)
 {
  if ($this->_resize_image() === TRUE)
  {
   $this->session->set_flashdata('message', 'Image has been resized');
   redirect(referrer());
  }
  else
  {
   $data['errors'] = $this->_errors;
   $this->load->vars($data);
  }
 }

 $this->load->view('image/edit_image');
}


function _resize_image()
{
 $config['image_library']  = 'gd2';
 $config['source_image']   = './uploads/' . $this->input->post('image');
 $config['maintain_ratio'] = $this->input->post('ratio') ? TRUE : FALSE;
 $config['width']          = $this->input->post('width');
 $config['height']         = $this->input->post('height');
 $this->load->library('image_lib');
 $this->image_lib->initialize($config);

 if ( ! $this->image_lib->resize())
 {
  return $this->_errors = $this->image_lib->display_errors('<div class="message error"><p>', '</p></div>');
 }
 return TRUE;
}

I will post a demo for all the Image Manipulation operations as soon as the series is finished. See you then :)

Categories: Web Development

Tags: codeigniter, php

No Comments

Comments