Step 14 – Crop and resize uploaded images in CodeIgniter

(created at: December 18, 2014; last update: December 18, 2014)
Being part of what is actually a larger tutorial, this step will assume that you’ve uploaded one or more image files through a form. So in this tutorial, which continues the previous step – Uploading multiple files (images) in CodeIgniter – I will assume that you’ve used a multiple attribute on the file input element. Also, I will assume that the array you will have after uploading the file(s) will have a structure just like the one in the image below.

Now, if you agree with the prelude of this tutorial, we can get to work. You can of course get to work even if you didn’t use multiple attribute on the file input element, but take care about accessing the array returned by the upload library.

We will continue to work in the same controller that we’ve built in the previous tutorial:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

  private $_uploaded;

  public function index()
  {
    $this->load->helper('form');
    $data['title'] = 'Multiple file upload';
    
    // let's consider that the form would come with more fields than just the files to be uploaded. If this is the case, we would need to do some sort of validation. If we are talking about images, the only method of validation for us would be to put the upload process inside a validation callback;
    $this->load->library('form_validation');

    //now we set a callback as rule for the upload field
    $this->form_validation->set_rules('uploadedimages[]','Upload image','callback_fileupload_check');
    
    //was something posted?
    if($this->input->post())
    {

      //run the validation
      if($this->form_validation->run())
      {
        // for now let's just verify if all went ok with the upload...
        echo '<pre>';
        print_r($this->_uploaded);
        echo '</pre>';
        // from here on you can do whatever you wish with the uploaded data or the other form fields that you might have. I decided to exit here, since this is not the object of our tutorial.
        exit;
      }
    }
    $this->load->view('upload_form', $data);
  }

  // now the callback validation that deals with the upload of files
  public function fileupload_check()
  {
    
    // we retrieve the number of files that were uploaded
    $number_of_files = sizeof($_FILES['uploadedimages']['tmp_name']);

    // considering that do_upload() accepts single files, we will have to do a small hack so that we can upload multiple files. For this we will have to keep the data of uploaded files in a variable, and redo the $_FILE.
    $files = $_FILES['uploadedimages'];

    // first make sure that there is no error in uploading the files
    for($i=0;$i<$number_of_files;$i++)
    {
      if($_FILES['uploadedimages']['error'][$i] != 0)
      {
        // save the error message and return false, the validation of uploaded files failed
        $this->form_validation->set_message('fileupload_check', 'Couldn\'t upload the file(s)');
        return FALSE;
      }
    }
    
    // we first load the upload library
    $this->load->library('upload');
    // next we pass the upload path for the images
    $config['upload_path'] = FCPATH . 'upload/';
    // also, we make sure we allow only certain type of images
    $config['allowed_types'] = 'gif|jpg|png';

    // now, taking into account that there can be more than one file, for each file we will have to do the upload
    for ($i = 0; $i < $number_of_files; $i++)
    {
      $_FILES['uploadedimage']['name'] = $files['name'][$i];
      $_FILES['uploadedimage']['type'] = $files['type'][$i];
      $_FILES['uploadedimage']['tmp_name'] = $files['tmp_name'][$i];
      $_FILES['uploadedimage']['error'] = $files['error'][$i];
      $_FILES['uploadedimage']['size'] = $files['size'][$i];
      
      //now we initialize the upload library
      $this->upload->initialize($config);
      if ($this->upload->do_upload('uploadedimage'))
      {
        $this->_uploaded[$i] = $this->upload->data();
      }
      else
      {
        $this->form_validation->set_message('fileupload_check', $this->upload->display_errors());
        return FALSE;
      }
    }
    return TRUE;
  }
}

 First thing first – What do we want to do with the uploaded images

Before we get to write the code, we must make sure we know what we want to do with the images we’ve uploaded. So allow me to share with you a real world scenario:

Since we’ve uploaded more than one file (image), I will suppose that this is for a photo gallery. So, we want the images to have a fixed width and height. This way we make sure the images of the photo gallery won’t break the site’s design. Also, when doing the cropping we want the cropped image to be taken from the center of the source image. We also want a thumbnail of the image with the same characteristics – a fixed width and height, center of the source image.

Let’s suppose our gallery will have images that are of of 620px by 400px. Also, the thumbnails will have to be 100px by 100px. Being thumbnails of the bigger images, we will append to the file name a ‘_thumb’ string.

Getting to work

To keep things tidy from the start we will do the image manipulation inside a separate method. As we don’t want this method to be accessible from the browser we will make it private, and we will call it from the method that is in direct connection with the user (in this case the index() method we’ve created in the previous step).

Let’s name the private method _image_creation(). The method will receive the array with the data regarding one source image (NOT THE ARRAY WE CREATED IN THE PREVIOUS STEP). This way, we will make sure that the method can be used even if the file input element doesn’t have the ‘multiple’ attribute (that is, if we have a form that doesn’t do a multiple file upload). This means that the method will receive an array that looks something like this:

Array
(
  [file_name] => mypic.jpg
  [file_type] => image/jpeg
  [file_path] => /path/to/your/upload/
  [full_path] => /path/to/your/upload/jpg.jpg
  [raw_name] => mypic
  [orig_name] => mypic.jpg
  [client_name] => mypic.jpg
  [file_ext] => .jpg
  [file_size] => 22.2
  [is_image] => 1
  [image_width] => 800
  [image_height] => 600
  [image_type] => jpeg
  [image_size_str] => width="800" height="200"
)

The private method will return an array with the images that were created. This way, we can use the new images’ names if we want to insert them in some sort of database:

private function _image_creation($image)
{
  // we make sure we receive an array. if no array is given or the array is empty, return false
  if(!is_array($image) || empty($image))
  {
    return FALSE;
  }
  // also let's make sure IT IS an image
  if($image['is_image']!=1)
  {
    return FALSE;
  }

  //let's have an array to return
  $new_images = array();

  //we return the array with the new images
  return $new_images;
}

The manipulation of the images will be done only after we’ve made sure the form validation ended with success and the images were uploaded. So, let’s modify that part of the method, so that instead of outputting the array it will output an array which will be received from the private method we’ve talked about before:

public function index()
{
  $this->load->helper('form');
  $data['title'] = 'Multiple file upload';

  // let's consider that the form would come with more fields than just the files to be uploaded. If this is the case, we would need to do some sort of validation. If we are talking about images, the only method of validation for us would be to put the upload process inside a validation callback;
  $this->load->library('form_validation');
  //now we set a callback as rule for the upload field
  $this->form_validation->set_rules('uploadedimages[]','Upload image','callback_fileupload_check');

  if($this->input->post())
  {
    if($this->form_validation->run())
    {
      // let's store the new created images' data inside an array for later use
      $created_images = array();
      foreach($this->_uploaded as $key => $source_image)
      {
        //from each source image we will create two images, the two images' data will be stored as an array for the source image's key
        $new_images = $this->_image_creation($source_image);
        $created_images[$key] = $new_images;
      }
      // now let's verify the new images have been created
      echo '<pre>';
      print_r($created_images);
      echo '</pre>';
      exit;
    }
  }
  $this->load->view('upload_form', $data);
}

Of course, you can test the return of the arrays by uploading one or more images, but for the moment you will just receive an empty array.

Now let’s turn to our _image_creation() method. First of all let’s make sure we have all the data: the width an height of the image and of the thumbnail, and what string will be appended to the thumbnail’s file name:

private function _image_creation($image)
{
  // we make sure we receive an array. if no array is given or the array is empty, return false
  if(!is_array($image) || empty($image))
  {
    return FALSE;
  }
  // also let's make sure IT IS an image
  if($image['is_image']!=1)
  {
    return FALSE;
  }

  //let's have an array to return
  $new_images = array();

  $image_width = 620;
  $image_height = 200;
  $thumb_width = 100;
  $thumb_height = 100;
  $thumb_name = '-thumb';
  // let's put the gallery images and thumbnails in a different directory (which will be public, of course... and writable) - make sure the directory exists
  $gallery_path = FCPATH.'media/gallery/';

  //we return the array with the new images
  return $new_images;
}

We load the library and set the first configurations:

// load the library
$this->load->library('image_lib');
// we set the image library that we want to be used
$config['image_library'] = 'gd2';
// we will take the source image from the $image array having the same source for the new image and the new thumbnail, we set the source here. of course you could use the new image as source for the thumbnail image, but after you've created the new image
$config['source_image'] = $image['full_path'];
// we set maintain_ratio to FALSE because we want do do a crop for the images
$config['maintain_ratio'] = FALSE;

Now, the tedious part. Calculating the width and height and also from where the crop will be made. I won’t explain you a lot here, because it has to do with the math of cropping and not with the image manipulation:

//calculate the source image's ratio
$source_ratio = $image['image_width'] / $image['image_height'];
//calculate the ratio of the new image
$new_ratio = $image_width / $image_height;
//if the source image's ratio is not the same with the new image's ratio, then we do the cropping. else we just do a resize
if($source_ratio!=$new_ratio)
{
  // if the new image' ratio is bigger than the source image's ratio or the new image is a square and the source image's height is bigger than it's width, we will take source's width as the width of the image
  if($new_ratio > $source_ratio || (($new_ratio == 1) && ($source_ratio < 1)))
  {
    $config['width'] = $image['image_width'];
    $config['height'] = round($image['image_width']/$new_ratio);
    // now we will tell the library to crop from a certain y axis coordinate so that the new image is taken from the vertical center of the source image
    $config['y_axis'] = round(($image['image_height'] - $config['height'])/2);
    $config['x_axis'] = 0;
  }
  else
  {
    $config['width'] = round($image['image_height'] * $new_ratio);
    $config['height'] = $image['image_height'];
    // now we will tell the library to crop from a certain x axis coordinate so that the new image is taken from the horizontal center of the source image
    $size_config['x_axis'] = round(($image['image_width'] - $config['width'])/2);
    $size_config['y_axis'] = 0;
  }
}

If after this, you still have some questions about how I did the calculation, I think it would be best for you to look at a great tutorial (if not all tutorials…) that can be found on CodeIgniter.tvCreate multiple aspect ratio thumbnails

Now what about the image name? We decided to put the new processed images inside the media/gallery directory, but what if a file with the name of the image we’ve just uploaded already exists? Then we must try a different name. So why not loop through possible names until we find a filename that doesn’t exist:

// how will we name the image? and what if the image name already exists in the gallery?
$image_path = $gallery_path.$image['file_name'];
$thumb_path = $gallery_path.$image['raw_name'].$thumb_name.$image['file_ext'];
$new_file = $image['file_name'];
$new_thumb = $image['raw_name'].$thumb_name.$image['file_ext'];
if(file_exists($image_path) || file_exists($thumb_path))
{
  // we will give it 100 tries. if after 100 tries it can't find a suitable name, then the problem is your imagination in naming the files that you've uploaded
  for($i=1;$i<=100;$i++)
  {
    $new_file = $image['raw_name'].'-'.$i.$image['file_ext'];
    $new_thumb = $image['raw_name'].'-'.$i.$thumb_name.$image['file_ext'];
    if(!file_exists($new_file))
    {
      $image_path = $gallery_path.$new_file;
      $thumb_path = $gallery_path.$new_thumb;
    }
  }
}
$config['new_image'] = $image_path;

Being a crop of image, which will be followed by a resize, we can set the quality of the new image to 100%. Why 100%? Because we don’t want that the quality of the new image to be 70% (from quality of the resize) from 70% (from the quality of the crop). I sure hope you understood this sentence…

// for cropping we want 100% image quality
$config['quality'] = '100%';

After we’ve set up the configuration is time to do the cropping and resizing and keep the eventual errors and the new file names and paths inside the array that will be returned from the method we’ve created:

//now we initialize the library providing it with the configuration
$this->image_lib->initialize($config);
// doing the cropping
if(!$this->image_lib->crop())
{
  // if errors occured, we must see what those errors were
  $errors[] = $this->image_lib->display_errors();
}

//let's clear the setting because we will need the library again
$this->image_lib->clear();

$config['maintain_ratio'] = TRUE;
$config['source_image'] = $image_path;
$config['width'] = $image_width;
$config['height'] = $image_height;
//for resising we want 70% image quality
$config['quality'] = '70%';
$this->image_lib->initialize($config);
if(!$this->image_lib->resize())
{
  $errors[] = $this->image_lib->display_errors();
}
$this->image_lib->clear();

$new_images['image'] = array('file_name'=>$new_file,'path'=>$config['new_image'],'errors'=>$errors);

Now, let’s create the thumbnail… We do this almost the same way we’ve created the image:

// PROCESS THE THUMBNAIL

// let's reset the errors
$errors = array();
// now we will do a reset for some of the $config array
$config['source_image'] = $config['new_image'];

//calculate the source image's ratio
$source_ratio = $image['image_width'] / $image['image_height'];
//calculate the ratio of the new image
$new_ratio = $thumb_width / $thumb_height;
//if the source image's ratio is not the same with the thumbnail image's ratio, then we do the cropping. else we just do a resize
if($source_ratio!=$new_ratio)
{
  // if the new image' ratio is bigger than the source image's ratio or the new image is a square and the source image's height is bigger than it's width, we will take source's width as the width of the image
  if($new_ratio > $source_ratio || (($new_ratio == 1) && ($source_ratio < 1)))
  {
    $config['width'] = $image['image_width'];
    $config['height'] = round($image['image_width']/$new_ratio);
    // now we will tell the library to crop from a certain y axis coordinate so that the new image is taken from the vertical center of the source image
    $config['y_axis'] = round(($image['image_height'] - $config['height'])/2);
    $config['x_axis'] = 0;
  }
  else
  {
    $config['width'] = round($image['image_height'] * $new_ratio);
    $config['height'] = $image['image_height'];
    // now we will tell the library to crop from a certain x axis coordinate so that the new image is taken from the horizontal center of the source image
    $size_config['x_axis'] = round(($image['image_width'] - $config['width'])/2);
    $size_config['y_axis'] = 0;
  }
}

// we've already set the thumb path when we looked for a name for the image
$config['new_image'] = $thumb_path;
// for cropping we want 100% image quality
$config['quality'] = '100%';
//now we initialize the library providing it with the configuration
$this->image_lib->initialize($config);
// doing the cropping
if(!$this->image_lib->crop())
{
  // if errors occured, we must see what those errors were
  $errors[] = $this->image_lib->display_errors();
}

//let's clear the setting because we will need the library again
$this->image_lib->clear();

$config['maintain_ratio'] = TRUE;
$config['source_image'] = $thumb_path;
$config['width'] = $thumb_width;
$config['height'] = $thumb_height;
//for resising we want 70% image quality
$config['quality'] = '70%';
$this->image_lib->initialize($config);
if(!$this->image_lib->resize())
{
  $errors[] = $this->image_lib->display_errors();
}
$this->image_lib->clear();

$new_images['thumb'] = array('file_name'=>$new_thumb,'path'=>$config['new_image'],'errors'=>$errors);

Now is the time for everyone to jump over my head and cry “BLASPHEMY! YOU DIDN’T RESPECT THE ‘DO NOT REPEAT YOURSELF’ RUUUUULE!!!”. Yes, I did repeat myself, by writing the same code twice (when calculating the sizes and doing the cropping and resizing), didn’t I? But I did show you how you can clean your code in previous tutorials. Why don’t you try to clean this code for a change?

Here is the final code for this and for the previous tutorial… and after that, if you think you are unable to clean the code, and you pay me with a beer, I will help you clean the code:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    private $_uploaded;

    public function index()
    {
        $this->load->helper('form');
        $data['title'] = 'Multiple file upload';

        // let's consider that the form would come with more fields than just the files to be uploaded. If this is the case, we would need to do some sort of validation. If we are talking about images, the only method of validation for us would be to put the upload process inside a validation callback;
        $this->load->library('form_validation');
        //now we set a callback as rule for the upload field
        $this->form_validation->set_rules('uploadedimages[]','Upload image','callback_fileupload_check');

        if($this->input->post())
        {
            if($this->form_validation->run())
            {
                // let's store the new created images' data inside an array for later use
                $created_images = array();
                foreach($this->_uploaded as $key => $source_image)
                {
                    //from each source image we will create two images, the two images' data will be stored as an array for the source image's key
                    $new_images = $this->_image_creation($source_image);
                    $created_images[$key] = $new_images;
                }
                // now let's verify the new images have been created. of course, as always don't do this at home. always output in a view file
                echo '<pre>';
                print_r($created_images);
                echo '</pre>';
                exit;
            }

        }
        $this->load->view('upload_form', $data);
    }

    public function fileupload_check()
    {
        // retrieve the number of images uploaded;
        $number_of_files = sizeof($_FILES['uploadedimages']['tmp_name']);
        // considering that do_upload() accepts single files, we will have to do a small hack so that we can upload multiple files. For this we will have to keep the data of uploaded files in a variable, and redo the $_FILE.
        $files = $_FILES['uploadedimages'];

        // first make sure that there is no error in uploading the files
        for($i=0;$i<$number_of_files;$i++)
        {
            if($_FILES['uploadedimages']['error'][$i] != 0)
            {
                $this->form_validation->set_message('fileupload_check', 'Couldn\'t upload the file(s)');
                return FALSE;
            }
        }

        // now, taking into account that there can be more than one file, for each file we will have to do the upload
        for ($i = 0; $i < $number_of_files; $i++)
        {
            $_FILES['uploadedimage']['name'] = $files['name'][$i];
            $_FILES['uploadedimage']['type'] = $files['type'][$i];
            $_FILES['uploadedimage']['tmp_name'] = $files['tmp_name'][$i];
            $_FILES['uploadedimage']['error'] = $files['error'][$i];
            $_FILES['uploadedimage']['size'] = $files['size'][$i];
            // we first load the upload library
            $this->load->library('upload');
            // next we pass the upload path for the images
            $config['upload_path'] = FCPATH . 'upload/';
            // also, we make sure we allow only certain type of images
            $config['allowed_types'] = 'gif|jpg|png';
            //now we initialize the upload library
            $this->upload->initialize($config);
            // we retrieve the number of files that were uploaded
            if ($this->upload->do_upload('uploadedimage'))
            {
                $this->_uploaded[$i] = $this->upload->data();
            }
            else
            {
                $this->form_validation->set_message('fileupload_check', $this->upload->display_errors());
                return FALSE;
            }
        }
        return TRUE;
    }

    private function _image_creation($image)
    {
        // we make sure we receive an array. if no array is given, return false
        if(!is_array($image) || empty($image))
        {
            return FALSE;
        }
        // also let's make sure IT IS an image
        if($image['is_image']!=1)
        {
            return FALSE;
        }

        //let's have an array to return
        $new_images = array();

        //some parameters
        $image_width = 620;
        $image_height = 200;
        $thumb_width = 100;
        $thumb_height = 100;
        $thumb_name = '-thumb';
        // let's put the gallery images and thumbnails in a different directory (which will be public, of course... and writable)
        $gallery_path = FCPATH.'media/galleries/';

        // PROCESS THE MAIN IMAGE

        // load the library
        $this->load->library('image_lib');
        // let's be prepared for any errors we may encounter
        $errors = array();
        // we set the image library that we want to be used
        $config['image_library'] = 'gd2';
        // we will take the source image from the $image array having the same source for the new image and the new thumbnail, we set the source here. of course you could use the new image as source for the thumbnail image, but after you've created the new image
        $config['source_image'] = $image['full_path'];
        // we set maintain_ratio to FALSE because we want do do a crop for the images
        $config['maintain_ratio'] = FALSE;


        //calculate the source image's ratio
        $source_ratio = $image['image_width'] / $image['image_height'];
        //calculate the ratio of the new image
        $new_ratio = $image_width / $image_height;
        //if the source image's ratio is not the same with the new image's ratio, then we do the cropping. else we just do a resize
        if($source_ratio!=$new_ratio)
        {
            // if the new image' ratio is bigger than the source image's ratio or the new image is a square and the source image's height is bigger than it's width, we will take source's width as the width of the image
            if($new_ratio > $source_ratio || (($new_ratio == 1) && ($source_ratio < 1)))
            {
                $config['width'] = $image['image_width'];
                $config['height'] = round($image['image_width']/$new_ratio);
                // now we will tell the library to crop from a certain y axis coordinate so that the new image is taken from the vertical center of the source image
                $config['y_axis'] = round(($image['image_height'] - $config['height'])/2);
                $config['x_axis'] = 0;
            }
            else
            {
                $config['width'] = round($image['image_height'] * $new_ratio);
                $config['height'] = $image['image_height'];
                // now we will tell the library to crop from a certain x axis coordinate so that the new image is taken from the horizontal center of the source image
                $size_config['x_axis'] = round(($image['image_width'] - $config['width'])/2);
                $size_config['y_axis'] = 0;
            }
        }

        // how will we name the image? and what if the image name already exists in the gallery?
        $image_path = $gallery_path.$image['file_name'];
        $thumb_path = $gallery_path.$image['raw_name'].$thumb_name.$image['file_ext'];
        $new_file = $image['file_name'];
        $new_thumb = $image['raw_name'].$thumb_name.$image['file_ext'];
        if(file_exists($image_path) || file_exists($thumb_path))
        {
            // we will give it 100 tries. if after 100 tries it can't find a suitable name, then the problem is your imagination in naming the files that you've uploaded
            for($i=1;$i<=100;$i++)
            {
                $new_file = $image['raw_name'].'-'.$i.$image['file_ext'];
                $new_thumb = $image['raw_name'].'-'.$i.$thumb_name.$image['file_ext'];
                if(!file_exists($new_file))
                {
                    $image_path = $gallery_path.$new_file;
                    $thumb_path = $gallery_path.$new_thumb;
                }
            }
        }
        $config['new_image'] = $image_path;
        // for cropping we want 100% image quality
        $config['quality'] = '100%';

        //now we initialize the library providing it with the configuration
        $this->image_lib->initialize($config);
        // doing the cropping
        if(!$this->image_lib->crop())
        {
            // if errors occured, we must see what those errors were
            $errors[] = $this->image_lib->display_errors();
        }

        //let's clear the setting because we will need the library again
        $this->image_lib->clear();

        $config['maintain_ratio'] = TRUE;
        $config['source_image'] = $image_path;
        $config['width'] = $image_width;
        $config['height'] = $image_height;
        //for resising we want 70% image quality
        $config['quality'] = '70%';
        $this->image_lib->initialize($config);
        if(!$this->image_lib->resize())
        {
            $errors[] = $this->image_lib->display_errors();
        }
        $this->image_lib->clear();

        $new_images['image'] = array('file_name'=>$new_file,'path'=>$config['new_image'],'errors'=>$errors);

        // PROCESS THE THUMBNAIL

        // let's reset the errors
        $errors = array();
        // now we will do a reset for some of the $config array
        $config['source_image'] = $config['new_image'];

        //calculate the source image's ratio
        $source_ratio = $image['image_width'] / $image['image_height'];
        //calculate the ratio of the new image
        $new_ratio = $thumb_width / $thumb_height;
        //if the source image's ratio is not the same with the thumbnail image's ratio, then we do the cropping. else we just do a resize
        if($source_ratio!=$new_ratio)
        {
            // if the new image' ratio is bigger than the source image's ratio or the new image is a square and the source image's height is bigger than it's width, we will take source's width as the width of the image
            if($new_ratio > $source_ratio || (($new_ratio == 1) && ($source_ratio < 1)))
            {
                $config['width'] = $image['image_width'];
                $config['height'] = round($image['image_width']/$new_ratio);
                // now we will tell the library to crop from a certain y axis coordinate so that the new image is taken from the vertical center of the source image
                $config['y_axis'] = round(($image['image_height'] - $config['height'])/2);
                $config['x_axis'] = 0;
            }
            else
            {
                $config['width'] = round($image['image_height'] * $new_ratio);
                $config['height'] = $image['image_height'];
                // now we will tell the library to crop from a certain x axis coordinate so that the new image is taken from the horizontal center of the source image
                $size_config['x_axis'] = round(($image['image_width'] - $config['width'])/2);
                $size_config['y_axis'] = 0;
            }
        }

        // we've already set the thumb path when we looked for a name for the image
        $config['new_image'] = $thumb_path;
        // for cropping we want 100% image quality
        $config['quality'] = '100%';
        //now we initialize the library providing it with the configuration
        $this->image_lib->initialize($config);
        // doing the cropping
        if(!$this->image_lib->crop())
        {
            // if errors occured, we must see what those errors were
            $errors[] = $this->image_lib->display_errors();
        }

        //let's clear the setting because we will need the library again
        $this->image_lib->clear();

        $config['maintain_ratio'] = TRUE;
        $config['source_image'] = $thumb_path;
        $config['width'] = $thumb_width;
        $config['height'] = $thumb_height;
        //for resising we want 70% image quality
        $config['quality'] = '70%';
        $this->image_lib->initialize($config);
        if(!$this->image_lib->resize())
        {
            $errors[] = $this->image_lib->display_errors();
        }
        $this->image_lib->clear();

        $new_images['thumb'] = array('file_name'=>$new_thumb,'path'=>$config['new_image'],'errors'=>$errors);
        //we return the array with the new images
        return $new_images;
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/Welcome.php */

Now if you visit your controller and upload a file or more than one file, you will be greeted with the result of the cropping and resizing of the images you’ve uploaded.

If you are scared of this really looooooooooong tutorial, you can, at any time, try my Image_nation library.

8 comments

  1. Foarte interesant articolul tau, din pacate nu am reusit sa-l parcurg pana la sfarsit. M-am oprit la linia 65 in Welcome.php si am realizat ca directia in care mergi tu nu este chiar cea optima. Majoritatea utilizatorilor folosesc camere foto sofisticate cu rezolutii mari, de cel putin 2 Mega pixeli. Ei doresc sa-si incarce cele 10-15 … 20 de fotografii facute in week-end direct pe website asa cum sunt ele, neprelucrate, si daca se poate, pe toate odata … Aici intervenim noi, web-developer-ii… trebuie sa facem sa se poata, altfel aplicatia noastra nu este “user-friendly” si ne pierdem utilizatorii. Din pacate, metoda clasica de incarcare a fisierelor pe server prin POST nu ne permite incarcarea in masa a fisierelor de mari dimensiuni. Un server admin responsabil care isi partajeaza eficient resursele va limita incarcarea fiserelor prin POST la 2/4 M. Metoda ta permite incarcarea fisierelor care sunt de mici dimensiuni si nu foarte multe. Si asta nu din cauza ta, ci pentru ca pur si simplu … “nu permite serverul”. Dar noi ca programatori putem “ocoli” aceste restrictii, fara a forta mana server-admin-ului, pentru a face ca aplicatia noastra sa fie “user-friendly” si sa ne tinem utilizatorii in permanenta conectati la website-ul nostru. Cum? Iti las tie placerea sa descoperi cele mai bune metode.

  2. Thank you again for giving us very nice tutorial. Yes, you’re right I need also image manipulation and I can’t believe you’ve made another one.

    Thank you very much!

  3. On running the above code , i am getting this error,the images are uploading but cropping,resizing and thumbnails are not there
    error is:

    Array
    (
    [0] => Array
    (
    [image] => Array
    (
    [file_name] => 2.jpg
    [path] => C:\xampp\htdocs\ci_regc/media/galleries/2.jpg
    [errors] => Array
    (
    [0] =>
    Unable to save the image. Please make sure the image and file directory are writable.

    [1] =>
    The path to the image is not correct.

    Your server does not support the GD function required to process this type of image.

    )

    )

    [thumb] => Array
    (
    [file_name] => 2-thumb.jpg
    [path] => C:\xampp\htdocs\ci_regc/media/galleries/2-thumb.jpg
    [errors] => Array
    (
    [0] =>
    The path to the image is not correct.

    Your server does not support the GD function required to process this type of image.

    [1] =>
    The path to the image is not correct.

    Your server does not support the GD function required to process this type of image.

    )

    )

    )

    )

    1. Hello, make sure that the directory in which you save the image is writable. Also, make sure you have GD Library installed.

Leave a Reply

Your email address will not be published.

No spam? * Time limit is exhausted. Please reload CAPTCHA.