Code snippets for symfony 1.x


Refine Tags

Snippets tagged "cache thumbnail"

Image cache to get any version of an image.

     * Image-cache script to convert and store images on-the-fly to any size.
     * (c) k at
     * You upload a lot of image assets to your site, but will need 
     * several sizes of them for various reasons. For example You'll need a big 
     * resolution version for downloading (original), also a smaller for previewing 
     * to the visitors and even another for an image-list page.
     * This script will create any version of the image using imagemagick and store 
     * it next to the original file. Images already generated are served without 
     * PHP, so You'll see no performance loss.
     * You define ImageMagick commands in this script, giving them aliases.
     * When You need an image converted, You sppecify the command in the URL of the 
     * image. If the image (of this size/version) does not exist yet, this script 
     * will generate it and save it next to the original image. The next time this 
     * image is requested, it will be served from the filesystem, without any 
     * overhead, thanks to the mod_rewrite rule You save into the image folder's 
     * .htaccess 
     * Requirement: ImageMagick installed in the server. See for information.
     * You will also need Apache with mod_rewrite.
     * EXAMPLE
     * Suppose You keep image assets under web/images, and have an image called greenfrog.jpg (size: 1200x1200px)
     * saved under web/images/animals/green/greenfrog.jpg. The image is accessible under
     * One day You realize that You need a 180x180px version of the image on the frontpage.
     * You can upload another variation, but with this script, you can just specify the new size in the URL, like this:
     * To be able to do this, You will need to save a .htaccess file into the 
     * images folder (see below), plus set the ImageMagick command associated with 180x180.
     * (The reson for the latter is security: if You run any command from the URL 
     * You open the door for DOS attacks.)
     * INSTALL
     * - save this script to the root of the images folder
     * - create a .htaccess file next to it, with this content: 
     * <IfModule mod_rewrite.c>
     *   RewriteEngine on
     *   RewriteCond %{REQUEST_FILENAME} !-f
     *   RewriteCond %{REQUEST_FILENAME} !-d
     *   RewriteRule ^(.*)$ index.php?img=$1 [L,QSA]
     * </IfModule>
     * - specify the commands You want to accept in the commands array
     * - modify the image URL-s to take advantage of the script.
     * - done :)
     * AFAIK all possible DOS attacks are handled (can't generate images forever),
     * plus the script takes care not allow access to files outside the 
     * directory it is saved to.
     * No guarantee or warranty of any kind!
     * TIP ME!
     * If You find this script useful, please consider giving me a tip!
     * Just follow this link to donate: 
    // find the convert command
    // you can hard-code it to make the srcipt faster, example:
    // $convert = '/usr/bin/convert';
    $convert = trim(shell_exec('which convert'));
    // this directory
    $thisDir = dirname(__FILE__).'/';
    // set commands via aliases
    $commands = array(
      '120x120' => '-geometry 120x120', // convert so no dimension is larger than 120px and keep ratio. For more commands see ImageMagick's documentation
    // die if no image is set
    if(!$img = $_GET['img']) die('no img');
    // make the filename safe to use
    //$img = strip_tags(htmlspecialchars($img));
    $img = trim($img);
    $img = str_replace('..', '', $img); // no going up in directory tree
    // get the command specified in the filename
    // example: big_green_frog.thumb150.jpg
    preg_match("/\.([^\.]*)\..{3}$/", $img, $match); // this also means no double commands (possible DOS attack)
    if(!$command = $match[1]) die('no command');
    if(!$commands[$command]) die('command does not exist');
    // get original filename
    // example: big_green_frog.jpg
    $imgFile = str_replace('.'.$command, '', $img, $replaceCount);
    // stop the possibility of creating unlimited files
    // example (attack): abc.120.jpg, abc.120.120.jpg, abc.120.....120.jpg - this could go on forever
    if($replaceCount > 1) die('command specified more than 1 time');
    // die if the original file does not exist
    if(!file_exists($thisDir.$imgFile)) die('original file does not exist');
    // prepare the command
    $preparedCommand = $convert .' '. $commands[$command] .' '. $thisDir . $imgFile .' '. $thisDir . $img;
    // run the conversion
    // redirect the browser to the new image - this is more reliable than fpassthru
    header("Location: http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/'.$img);
by karoly sz on 2009-07-25, tagged cache  convert  image  imagemagick  resize  thumbnail 

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 
(1 comment)