CakePHP Thumbnail Helper

Published: on 8/7/08 | Comments (5)

Today I've been working on generating thumbnails using the excellent phpThumb library, and integrating it into a CakePHP application I am writing.

In case you've not come across it before, phpThumb uses the GD library to create thumbnails from images (JPEG, PNG, GIF, BMP, etc) on the fly. The output size is configurable (can be larger or smaller than the source), and the source may be the entire image or only a portion of the original image. True color and resampling is used if GD v2.0+ is available, otherwise paletted-color and nearest-neighbour resizing is used. ImageMagick is used wherever possible for speed. Basic functionality is available even if GD functions are not installed (as long as ImageMagick is installed).

Now, I've seen phpThumb integrated with CakePHP as a controller, and as a component, but what I needed for this project and what seemed the most logical implementation, was to integrate it as a helper file, available directly to the view.

Getting Started

OK, first things first, in order to use phpThumb, we need to download a copy from here, and place the files in to folder called phpThumb in either the app/vendors, or vendors folder.

Now copy and paste the following into a file called app/views/helpers/thumbnail.php

<?php
class ThumbnailHelper extends AppHelper {
    function render($image,$params){
        //Set defaults
        $path='';
        $width=150;
        $height=225;
        $quality=75;
        //Extract Parameters
        if(isset($params['path'])){
            $path = $params['path'].DS;
        }
        if(isset($params['width'])){
            $width = $params['width'];
        }
        if(isset($params['height'])){
            $height = $params['height'];
        }
        if(isset($params['quality'])){
            $quality = $params['quality'];
        }
        //import phpThumb class
        app::import('Vendor','phpthumb',array('file'=>'phpThumb'.DS.'phpthumb.class.php'));
        $thumbNail = new phpthumb;
        $thumbNail->src = WWW_ROOT.'img'.DS.$path.$image;
        $thumbNail->w = $width;
        $thumbNail->h = $height;
        $thumbNail->q = $quality;
        $thumbNail->config_imagemagick_path = '/usr/bin/convert';
        $thumbNail->config_prefer_imagemagick = true;
        $thumbNail->config_output_format = 'jpg';
        $thumbNail->config_error_die_on_error = true;
        $thumbNail->config_document_root = '';
        $thumbNail->config_temp_directory = APP . 'tmp';
        $thumbNail->config_cache_directory = WWW_ROOT.'img'.DS.'thumbs'.DS;
        $thumbNail->config_cache_disable_warning = true;
        $cacheFilename = $image;
        $thumbNail->cache_filename = $thumbNail->config_cache_directory.$cacheFilename;
        if(!is_file($thumbNail->cache_filename)){
            if($thumbNail->GenerateThumbnail()) {
                $thumbNail->RenderToFile($thumbNail->cache_filename);
            }
        }
        if(is_file($thumbNail->cache_filename)){
            return $cacheFilename;
        }
    }
}
?>

Now create a folder called thumbs in your app/webroot/img folder and you are ready to go.

Basically, whats happening within the helper is as follows: * First off we check for any passed parameters to override the defaults, the available parameters are path, width, height and quality, path a path within your img folder which holds the images you wish to create the thumbnail of, by default this is null, and if you don't specify it, then the helper will look directly in the img folder. width and height default to 200 and 325 if you don't set them and quality defaults to 75 for image quality. * Next the helper imports the phpThumb class and instantiates it as thumbNail * With thumbNail instatiated we now go through setting the object up, and if a thumbnail has not already been cached, then a new cache file is created. * Finally, the cached file is returned ready to be displayed using $html->image().

Note For this helper, I have kept things fairly simple as all I needed for this application is jpg support, therefore, I have hard coded this in to the helper, you could of course adapt the code to check for file extension and alter the configuration accordingly, but that is beyond the scope of this example.

In Use

In order to use the Thumbnail Helper, add it to the $helpers array of the controller you are working with (or app_controllers if you need it available system wide) with the line:

var $helpers = array('Thumbnail');

Then within your view file you can do something like the following:

echo $html->image(
            'thumbs/'.$thumbnail->render(
                'picture01.jpg',
                array(
                    'path'=>'pictures',
                    'width'=>100,
                    'height'=>150,
                    'quality'=>80
                )
            )
        );

Which will create a thumbnail version of an image called picture01.jpg in the folder app/webroot/img/pictures, save a cached version as app/webroot/img/thumbs/picture01.jpg, and return this filename to be displayed by the $html->image() helper.

That's it for now,

happy baking!

Comments

Have your say:





Please enter the code