phpThumb Helper

This article is also available in the following languages:
By DanielMedia
Here's a simple phpThumb helper with built in cache support. If an image is already cached when using this helper, it just displays the cached image tag without having to instantiate a phpThumb object.

Note: I haven't done any sort of testing with this helper on a production website. Only on a dev site so there's a chance some bugs could creep in that I haven't experienced yet.

Setup


Download a copy of phpThumb and place it in your Vendors directory.

Note: I renamed the phpThumb folder from "phpThumb_1.7.8" to just "phpThumb". If you plan to keep the default folder name, just change the import statement in the helper.


Usage


Simple example


<? $thumbnail->show($options, $tag_options); ?>

Verbose example



<?
$thumbnail->show(
    // This is the options array for creating the thumbnail
    array(
    //Save path - (Required) - The path to save the thumbnail to if its not already cached
    'save_path' => $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/assets/images/thumbs',
    //Display path - (Required) - The path to show in the image tag output
    'display_path' => '/assets/images/thumbs', // or 'display_path' => 'http://images.domain.com',
    //Error image path - (Required) - The image to show if something goes wrong with rendering a thumbnail
    'error_image_path' => '/assets/images/error.jpg',
    // From here on out, you can pass any standard phpThumb parameters
    // Note: for phpThumb at least the src property is required.
    'src' => '/app/webroot/assets/images/Dan.jpg', 
    'w' => 300, 
    'h' => 200,
    'q' => 100,
    'zc' => 1
    ),
    // This is the tag options array for adding any other properties to the image tag
    array('style' => 'border: 1px solid #000;')
);
?>

Save the helper below as "thumbnail.php" in /app/views/helpers:


Helper Class:

<?php 
App
::import('Vendor''phpThumb', array('file' => 'phpThumb'.DS.'phpthumb.class.php'));

class 
ThumbnailHelper extends Helper    {
    
    private 
$php_thumb;
    private 
$options;
    private 
$tag_options;
    private 
$file_extension;
    private 
$cache_filename;
    private 
$error;
    
    private function 
init($options = array(), $tag_options = array())    {
        
$this->options $options;
        
$this->tag_options $tag_options;
        
$this->set_file_extension();
        
$this->set_cache_filename();
        
$this->error '';
    }
    
    private function 
set_file_extension()    {
        
$this->file_extension substr($this->options['src'], strrpos($this->options['src'], '.'), strlen($this->options['src']));
    }
    
    private function 
set_cache_filename()    {
        
ksort($this->options);
        
$filename_parts = array();
        
$cacheable_properties = array('src''new''w''h''wp''hp''wl''hl''ws''hs''f''q''sx''sy''sw''sh''zc''bc''bg''fltr');
        foreach(
$this->options as $key => $value)    {
            if(
in_array($key$cacheable_properties))    {
                
$filename_parts[$key] = $value;
            }
        }
        
        
$this->cache_filename '';
        foreach(
$filename_parts as $key => $value)    {
            
$this->cache_filename .= $key $value;
        }
        
$this->cache_filename $this->options['save_path'] . DS md5($this->cache_filename) . $this->file_extension;
    }
    
    private function 
image_is_cached()    {
        if(
is_file($this->cache_filename))    {
            return 
true;
        } else    {
            return 
false;
        }
    }
    
    private function 
create_thumb()    {
        
$this->php_thumb = new phpThumb();
        foreach(
$this->php_thumb as $var => $value) {
            if(isset(
$this->options[$var]))    {
                
$this->php_thumb->setParameter($var$this->options[$var]);
            }
        }
        if(
$this->php_thumb->GenerateThumbnail()) {
            
$this->php_thumb->RenderToFile($this->cache_filename);
        } else {
            
$this->error ereg_replace("[^A-Za-z0-9\/: .]"""$this->php_thumb->fatalerror);
            
$this->error str_replace('phpThumb v1.7.8200709161750'''$this->error);
        }
    }
    
    private function 
show_image_tag()    {
        if(
$this->error != '')    {
            
$src $this->options['error_image_path'];
            
$this->tag_options['alt'] = $this->error;
        } else    {
            
$src $this->options['display_path'] . '/' substr($this->cache_filenamestrrpos($this->cache_filenameDS) + 1strlen($this->cache_filename));
        }
        
$img_tag '<img src="' $src '"';
        if(isset(
$this->options['w']))    {
            
$img_tag .= ' width="' $this->options['w'] . '"';
        }
        if(isset(
$this->options['h']))    {
            
$img_tag .= ' height="' .  $this->options['h'] . '"';
        }
        foreach(
$this->tag_options as $key => $value)    {
            
$img_tag .= ' ' $key '="' $value '"';
        }
        
$img_tag .=  ' />';
        
        echo 
$img_tag;
    }
    
    public function 
show($options = array(), $tag_options = array())    {
        
$this->init($options$tag_options);
        if(
$this->image_is_cached())    {
            
$this->show_image_tag();
        } else    {
            
$this->create_thumb();
            
$this->show_image_tag();
        }
    }
    
}
?>

Comments

  • Posted 07/18/09 01:38:39 PM
    Sebastian,

    Post your code on my blog in the comments and I can try to help you out. Note that the helper code has changed since this bakery article. You can find the new code here:

    http://code621.com/content/1/phpthumb-helper-for-cakephp
  • Posted 07/18/09 12:23:10 PM
    Hi,

    I'd like to use this helper but I've got some problems with it.

    I've made it like you wrote, but I only get non-existing images in my browser and an empty thumb folder.

    I think my configuration should be correct and I've set enough memory (20M) in the php.ini.

    I've no idea what to do now...

    Best regards, Sebastian
  • Posted 06/19/09 02:16:19 PM
    @Barry: Thanks for your suggestions. I will look into the width/height issue. In regard to checking if the file has changed, I added that a little while back already. Please check out my blog to get the updated code for this helper: http://code621.com/content/1/phpthumb-helper-for-cakephp
  • Posted 06/19/09 01:50:21 AM
    If you add this code inside of the if statement within your image_is_cached() function, it will also check to see if the original image has been modified since the cache file was generated.

    $modified = filemtime($this->cache_filename);
    $original = WWW_ROOT . str_replace('/',DS,$this->options['src']);
    $omodified = filemtime($original);

    if($omodified > $modified) return false;
  • Posted 06/11/09 10:24:32 AM
    While I was using this I noticed that you were putting the width and height in the actual img tag after the thumb had been resized. This will cause distortion in many instances because the convert command will make the image fit "in the box" while maintaining the aspect ratio. The img tag will stretch the image to fit those exact dimensions though.
  • Posted 06/07/09 07:26:35 PM
    Thanks you very much for contributing this.
  • Posted 06/04/09 07:46:09 PM
    This helped me
  • Posted 04/30/09 06:50:33 PM
    wow, thx, soon on production
  • Posted 01/03/09 01:15:25 PM

    $this->error = str_replace('phpThumb v1.7.8200709161750', '', $this->error); 
    it's not a good idea hardcode the version number here...

    anyway this helper doesn't work for me...
    the error is:
    thissourceFilename and thissrc are both empty
  • Posted 10/27/08 07:29:25 PM
    Thank you for this helper, found it quite flexible.
  • Posted 08/23/08 08:29:18 AM
    No exmple is described on this topic, It would be better to have at least one really working example. Thank you
  • Posted 07/30/08 12:33:00 AM
    I particularly like the part where cached images are shown directly - Good work

Comments are closed for articles over a year old