Step 14 – Crop and resize uploaded images in CodeIgniter

Created at: December 18, 2014; Last update: January 23, 2015

(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.

files_locations

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:

 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:

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:

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:

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:

We load the library and set the first configurations:

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:

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:

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…

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, let’s create the thumbnail… We do this almost the same way we’ve created the image:

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:

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 thoughts on “Step 14 – Crop and resize uploaded images in CodeIgniter

  1. Crisalin Petrovschi

    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.

    Reply
  2. rodge

    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!

    Reply
  3. Gaurav Rai

    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.

    )

    )

    )

    )

    Reply
    1. avenirer Post author

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

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

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