You are on page 1of 5

CakePHP Thumbnail Helper http://www.studiocanaria.com/articles/cakephp_thumbnail_...

Studio Canaria
Home (/) | About (/subjects/studio_canaria) | Contact (/enquiries/send)

CakePHP Thumbnail Helper


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

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
(http://phpthumb.sourceforge.net/) , 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

1 of 5 09/22/2008 03:26 PM
CakePHP Thumbnail Helper http://www.studiocanaria.com/articles/cakephp_thumbnail_...

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',

2 of 5 09/22/2008 03:26 PM
CakePHP Thumbnail Helper http://www.studiocanaria.com/articles/cakephp_thumbnail_...

'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
1: Robert (http://blog.matsimitsu.nl) says
on 8/7/08

Nice helper! i think this is a nice solution, but i'd change the code to include the image size in the thumbnail
name, so you can have multiple sizes of an image.

2: Peter Butler (http://studiocanaria.com) says


on 11/7/08

@Robert - Great idea, and to implement it simple change line 37 of the above code snippet from

$cacheFilename = $image;

to:

$cacheFilename = $width.'x'.$height.'_'.$image;

I didn't need this functionality on the application I built this for, but it does improve the reusability, many thanks
for your comment.

3: Abba Bryant says


on 28/7/08

Also, with the new file dimensions in the name ( or even better would be subfolder naming ) you could check to
see if it exists before creating it.

4: TommyO says
on 31/7/08

Excellent! Although I tend to lean towards raw code rather than using 3rd party stuff whenever possible, this is
simple and clean and the fact that these libs even have their own caching mechanism is great.

This makes a compelling argument for ImageHelper logic, where the behaviors and components just don't fit
right.

3 of 5 09/22/2008 03:26 PM
CakePHP Thumbnail Helper http://www.studiocanaria.com/articles/cakephp_thumbnail_...

I'd love a way to preset all the options for pages with multiple images, so if you ever feel the need to expand
on this guy... ;)

Well done.

5: Daa says
on 19/8/08

Hi, Thanks for your helper, How can I use this helper for gif and png images.

Thanks

Have your say:

Name (Required)

Email Address (Required but not published)

Web Site (Optional)

Validation Code (Shown Below)

Comment

S ubmit

About Studio Canaria


Studio Canaria is the web site of freelance web developer, Peter Butler. Articles on this site relate to designing,
developing and marketing modern web applications.

(http://feeds.feedburner.com/studiocanaria)

Read About...
Studio Canaria (/subjects/studio_canaria)
CakePHP (/subjects/cakephp)
Case Studies (/subjects/case_studies)
Web Development Resources (/subjects/web_development_resources)
Gran Canaria (/subjects/gran_canaria)

Recent Comments
kiran aghor on Web Development Resources - Aptana Studio (/articles
/web_development_resources_aptana_studio#c789) : I use netbeans 6.5 for php (beta and nightly). It is really

4 of 5 09/22/2008 03:26 PM
CakePHP Thumbnail Helper http://www.studiocanaria.com/articles/cakephp_thumbnail_...

good. (ur captcha is very difficult)


hepper on Web Development Resources - Aptana Studio (/articles
/web_development_resources_aptana_studio#c788) : Just fund your blog and it looks like you cover some
interesting topics. I'm use Eclipse PDT...
Henk on CakePHP Auth Component - Users, Groups & Permissions Revisited (/articles
/cakephp_auth_component_users_groups_permissions_revisited#c787) : Unbelievable, I found it! It was my
favicon.ico which wasn't on the right spot.
Henk on CakePHP Auth Component - Users, Groups & Permissions Revisited (/articles
/cakephp_auth_component_users_groups_permissions_revisited#c786) : Hi Peter, Great article! But in Firefox 3
I have to login 2 times before I am logged in. IE...
ndlm on CakePHP Auth Component - Users, Groups & Permissions (/articles
/cakephp_auth_component_users_groups_permissions_1#c785) : Hello! i'm new in php and cakephp things. i
implement the code that you have in the tutori...

Beginning CakePHP
Learn more about the CakePHP framework with this new book!
www.apress.com

iStock Photos & Images


Over 3 million Quality Photos Quick Search, Easy Download!
iStockphoto.com

J2EE W eb Thumbnail Images


Create web thumbnails in Java with WebRenderer SE browser
SDK
www.webrenderer.com

Bangkok In Pictures
NYTimes.com has photos and sightseeing ideas in Bangkok
www.nytimes.com/travel

© 2008 Studio Canaria - All Rights Reserved

5 of 5 09/22/2008 03:26 PM

You might also like