Simple thumbnail generator helper for CakePHP

This simple CakePHP helper class will create thumbnails of images for you. Most of this code was actually taken from an other website (here) so I can’t claim all the credit but I did make it a little smarter.

I added checking for the thumbnail so its not re generated every time. This will save you some CPU cycles and load time for the users.

You would call it with something like this

$image->resize('image.jpg', 100, 100, true,array('border'=>'0', 'alt'=>'My Image')

1. To use it you should make a folder called /webroot/img/imagecache and make sure it is writable to all.
2. Create a file called /views/helpers/image.php and copy the following code into it.

<?php
class ImageHelper extends Helper {
	var $helpers = array('Html'); 
	var $cacheDir = 'imagecache';
 
	function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
		$types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type 
 
		$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this-&gt;themeWeb.IMAGES_URL;
 
		$url = $fullpath.$path;
 
		if (!($size = getimagesize($url)))
			return; // image doesn't exist
 
		if ($aspect) { // adjust to aspect.
			if (($size[1]/$height) &gt; ($size[0]/$width))  // $size[0]:width, [1]:height, [2]:type
				$width = ceil(($size[0]/$size[1]) * $height);
			else
				$height = ceil($width / ($size[0]/$size[1]));
		}
 
		$relfile = $this-&gt;cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file
		$cachefile = $fullpath.$this-&gt;cacheDir.DS.$width.'x'.$height.'_'.basename($path);  // location on server
 
		if (file_exists($cachefile)) {
		$csize = getimagesize($cachefile);
		$cached = ($csize[0] == $width &amp;&amp; $csize[1] == $height); // image is cached
		if (@filemtime($cachefile) &lt; @filemtime($url)) // check if up to date
			$cached = false;
		} else {
			$cached = false;
		}
 
		if (!$cached) {
			$resize = ($size[0] &gt; $width || $size[1] &gt; $height) || ($size[0] &lt; $width || $size[1] &lt; $height);
		} else {
			$resize = false;
		}
 
		if ($resize) {
			$image = call_user_func('imagecreatefrom'.$types[$size[2]], $url);
			if (function_exists("imagecreatetruecolor") &amp;&amp; ($temp = imagecreatetruecolor ($width, $height))) {
				imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
			} else {
				$temp = imagecreate ($width, $height);
				imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
			}
				call_user_func("image".$types[$size[2]], $temp, $cachefile);
				imagedestroy ($image);
				imagedestroy ($temp);
		}
		return $this-&gt;output(sprintf($this-&gt;Html-&gt;image($relfile,$htmlAttributes)));
    }
}
?>

You can see it in action at http://www.rewardchamp.com, the rewards box towards the top has the thumbnail images showing.