Create thumbnails on the fly with CodeIgniter

Before explaining the solution, you should know creating thumbnails on the fly is server inefficient, eats a lot of resources and they should be generated as soon as the images are uploaded. However, there are some occasions when we absolutely need to generate thumbs on the fly. In this article we will learn how to do this in CodeIgniter.

To start, create a new Controller class and name it something like “Thumbs”. You can have many methods inside your controller to handle additional paths or different settings. In this case only have a products() method, but you can have as many as you like.

class Thumbs extends Controller {

	public function __construct()
	{
		parent::Controller();
		$this->load->library('image_lib');
	}

	public function products($width, $height, $img)
	{
		$config['source_image']	= 'assets/main/images/products/'.$img;
		$config['width'] = $width;
		$config['height'] = $height;
		$config['dynamic_output'] = true;

		$this->image_lib->initialize($config);
		$this->image_lib->resize();
	}

}

Then, whenever you need an image with a thumbnail on the fly, call the controller directly in your path, like this:

<img src="thumbs/products/158/158/myimage.jpg" alt="" />

The method will look for myimage.jpg in assets/main/images/products/ (you can edit this path of course) and will output the resized image according to the dimensions we passed to the function.

    • Fernando
    • September 28th, 2010 7:44pm

    Hi, I’m from Brazil.

    I need thumbs of many diffrent sizes and I think that this is the better solution/option for me.

    Thank you for the post. It was helpful to me.

  1. Hi!

    I’m from Russia.

    I checked tons of posts about image resize on the fly with CI.
    And found only one real solution. It’s yours!

    This thing works!

    Thanks, man!

    • Peter Mitchell
    • June 12th, 2011 6:32am

    This process is not server inefficient if you cache the images generated rather than outputting them dynamically.

    Furthermore passing the image dimensions to the controller directly leaves the system open to malicious attack.

    It would be prudent to specify some presets in an array then call them

    I.e. array( 'sml' => '100x100', 'med' => '400x400' );
    

    etc

  2. Yes , i agree with peter. Don’t use the width and height on the url.

    Because anyone can call the same with different width and height values , it will fill your server space…

    So store the dimensions in an array , and cross check with the calling url’s width and height.

    • gabriel
    • November 17th, 2011 6:49am

    Hello!

    Is there any special configuration to work? In my script is not working.

    Thx!

    • Anantha Reddy
    • December 24th, 2011 8:31am

    Hello !

    This is Anantha Reddy from Inida.

    Very thankful for this post. It was very useful for me.

    Thank you

  1. No trackbacks yet.

follow me on Twitter