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.
Update 08/11/2012: in order to prevent the PHP engine from generating the same thumbnail over and over again on each page load, this new snippet of code will actually try to read the thumbnail before creating it. For it to work, you need a “thumbs” folder where all the generated thumbs will be saved.
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) { // Checking if the file exists, otherwise we use a default image $img = is_file('assets/main/images/products/'.$img) ? $img : 'default.jpg'; // If the thumbnail already exists, we just read it // No need to use the GD library again if( !is_file('assets/main/images/products/thumbs/'.$width.'x'.$height.'_'.$img) ) { $config['source_image'] = 'assets/main/images/products/'.$img; $config['new_image'] = 'assets/main/images/products/thumbs/'.$width.'x'.$height.'_'.$img; $config['width'] = $width; $config['height'] = $height; $this->image_lib->initialize($config); $this->image_lib->resize_crop(); } header('Content-Type: image/jpg'); readfile('assets/main/images/products/thumbs/'.$width.'x'.$height.'_'.$img); } }
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.