Code snippets for symfony 1.x


get cached Thumbnail helper

This helper return path to a generate (and cached) thumbnail for an image and sizes given.

First it checks if the thumbnail as ever been created for the given size. If not, it created it and return the path to the thumbnail. Else, it will only return the path to the thumbnail.

Thumbnails are stored in a sub-directory of the original image named like [width]x[height].

examples : product/foobar.jpg which is 640x480 images - getThumbnail (320x320) will the first time generate the thumbnail "product/320x320/foobar.jpg", and return the path to this image.

parameters : - $image_path should be the path and filename of the image under uploads directory. ex: product/foobar.jpg - $width is the maximal thumbnail width - $height is the maximal thumbnail height

function getThumbnail($image,$width=null,$height=null, $scale = true, $inflate = true, $quality = 75)
    if ($width>0) $thumbnail_dir.=$width;
    if ($height>0) $thumbnail_dir.='x'.$height;
    if ($width>0 || $height>0) $thumbnail_dir.='/';
    if (!file_exists(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir.$image_file) && ($width!=null || $height!=null))
      if (!is_dir(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir))
        mkdir (sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir,0777);
      $thumbnail = new sfThumbnail($width, $height,$scale,$inflate,$quality); 
    return '/uploads'.'/'.$image_dir.'/'.$thumbnail_dir.$image_file;

This is very usefull to use it in model like this :

In model :

  public function getThumbnail($width=null,$height=null)
    return getThumbnail('product/'.$this->getImage(),$width,$height);

in template :

<?php foreach ($products as $product) { ?>
<li><?php echo image_tag($product->getThumbnail(150,100)); ?></li>
<?php } ?>

limitation : - work on images of upload directories only (other dir might have permission problem) - the check of thumbnail existance don't take care of scale and inflate values. It is easy to update the code to stored thumbnail in different subdirectory according to these parameters.

by Sylvain PAPET on 2007-09-23, tagged cache  helper  thumbnail 

Comments on this snippet

gravatar icon
#1 Raphael Ara├║jo on 2009-04-08 at 06:52

Hi Sylvain, i have a idea for you. I liked very much your code, but the cache images didnt delete when if update register. So I make de code:

[php] protected function doSave($con = null) { // delete cache files $this->removeThumbs(sfConfig::get('sf_upload_dir').'/produtos/', $this->getObject()->getImagem());

return parent::doSave($con);


protected function removeThumbs($dir, $image, $sub = false) { if(!$dh = @opendir($dir)) { return; } while (false !== ($obj = readdir($dh))) { if($obj == '.' || $obj == '..' || $obj == '.svn') { continue; }

  if (is_dir($dir.&#039;/&#039;.$obj))
    $this-&gt;removeThumbs($dir.&#039;/&#039;.$obj, $image, true);
  else if ($sub &amp;&amp; $obj == $image)

} [/php]