Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "thumbnail"

Thumbnails creation in view (like sorl in django)

function thumbnail($path, $maxWidth, $maxHeight, $params=null)
{
    $path = ($path{0} == '/' ? '' : '/') . $path;
 
    $maxWidth = (int) $maxWidth;
    $maxHeight = (int) $maxHeight;
 
    $fileName = @end(explode('/', $path));
 
    $thumbsDir = sfConfig::get('sf_web_dir').'/images/thumbs';
    if(!file_exists($thumbsDir)) {
        mkdir($thumbsDir);
        chmod($thumbsDir, 0777);
    }
 
    $thumbName = $fileName.'-'.$maxWidth.'x'.$maxHeight.'.png';
    $thumbPath = '/images/thumbs/'.$thumbName;
 
    $sourcePath = sfConfig::get('sf_web_dir').$path;
    $destPath = sfConfig::get('sf_web_dir').$thumbPath;
 
    if(!file_exists($destPath)) {
        $t = new sfThumbnail($maxWidth, $maxHeight);
        $t->loadFile($sourcePath);
        $t->save($destPath, 'image/png'); 
    }
 
    $path = $thumbPath;
    return image_tag($path, $params);
 
}
 

Usage similar to image_tag, directory web/images/thumbs with chmod 0777 need to be created. Depending on sfThumbnailPlugin

example:

echo thumbnail('bigPhoto.png', 100, 100, 'alt=myBigPhoto');
 
by Adam ZieliƄski on 2010-03-06, tagged thumbnail 

Image cache to get any version of an image.

<?php
    /**
     * IMAGECACHE
     *
     * Image-cache script to convert and store images on-the-fly to any size.
     * (c) k at isr.hu
     *
     * THE PROBLEM
     *
     * 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.
     *
     * HOW IT WORKS
     *
     * 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 http://www.imagemagick.org/ 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
     * http://www.you.com/images/animals/green/greenfrog.jpg
     * 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:
     * http://www.you.com/images/animals/green/greenfrog.180x180.jpg
     *
     * 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 :)
     *
     * SECURITY
     *
     * 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: 
     * https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=7030104
     **/
 
    // 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
    shell_exec($preparedCommand);
 
    // redirect the browser to the new image - this is more reliable than fpassthru
    header("Location: http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/'.$img);
    exit;
    ?>
 
by karoly sz on 2009-07-25, tagged cache  convert  image  imagemagick  resize  thumbnail 

Thumbnail with propel

A simple class to generate thumbnail linked to the propel model. sfThumbnailPlugin is needed and sfPropelPlugin (of course)

Override two methods create one, add a constant and go !

Give me your opinion !

You need to add into peer class (MediaPeer in exemple) :

<?php
 
class MediaPeer extends BaseMediaPeer
{  
  // directory of file (under uploads file)
  const IMAGE_DIR = 'images/media';
 
  // override
  public static function doDelete($values, PropelPDO $con = null)
  {
    // delete every image file linked
    return sfPropelThumbnail::deleteThumb($values,$con, 'Media');
  }
 
  // Configuration
  public static function getThumbConfig()
  {
 
    return  array( 'image'=>  // each fields to thumbnailize
               array(         // each thumbnail configuration for field
                    array('thumb_dir' => 'thumbnail', 'size' => array(200, 500)),
                    array('thumb_dir' => 'fullsize' , 'size' => array(500, 700), 'crop'=>true),
                    array('thumb_dir' => 'verysmall', 'size' => array(60,60)   , 'crop'=>true)
                    )
                );
  }
}
 

And into your model class (Media in exemple) :

<?php
 
class Media extends BaseMedia
{
  public function setImage($value, $thumb=true)
  {
    // if first call thumbnailize image and after put file name in the db
    if($thumb)
      sfPropelThumbnail::generateThumbnail($value,$this ,'Media', 'image');
    else 
      parent::setImage($value);
  }
} 
 

sfPropelThumbnail

<?php
 
/*
 * @author: Simon Bonjean (sim@45-ouest.be)
 */
 
class sfPropelThumbnail {
  /*
   *  getConfiguration
   */
  protected static function getDefaultConfig($class)
  {
    $dir       = constant($class .'Peer::IMAGE_DIR');     
    $configs   = call_user_func(array($class .'Peer','getThumbConfig')); 
    return array($dir, $configs);
  }
 
  /*
   * Generate the thumbnails
   */
  public static function generateThumbnail($value,$that,$class,$fields_name)
  {
 
    // Variable 
    $upload_path = sfConfig::get('sf_upload_dir');         // Get path to upload
    list($dir, $configs) = self::getDefaultConfig($class); // Get Config and dir name
    $configs = $configs[$fields_name];                     // Get config for name
    $methode = 'set'.ucfirst($fields_name);                // Get Methode 
 
    if(empty($value)) 
    {
      // delete all thumbs
      foreach($configs as $config) {
         $thumb_dir = $config['thumb_dir'];
        if(is_file($upload_path . "/$dir/$fields_name/$thumb_dir/" . $that->getImage()))
            unlink($upload_path . "/$dir/$fields_name/$thumb_dir/" . $that->getImage() );
      }
      // Set l'image sans faire de thumb
 
      call_user_func(array($that,$methode),$value, false);
 
    } else {
      // delete old thumb
      foreach($configs as $config){
        $thumb_dir = $config['thumb_dir'];
        if(is_file($upload_path."/$dir/$fields_name/$thumb_dir/".$that->getImage()))
          unlink( $upload_path . "/$dir/$fields_name/$thumb_dir/".$that->getImage() );
      }
 
      // Set l'image sans faire de thumb 
      call_user_func(array($that,$methode),$value, false);
      // generate each thumbs
      foreach($configs as $config) {
 
        $thumb_dir = $config['thumb_dir'];
        $size      = $config['size']; 
 
 
        // CREATE DIRECTORY IF NOT EXIST !!!
 
        if(!is_dir($upload_path."/$dir/"))
            mkdir($upload_path."/$dir/");                           // base name
        if(!is_dir($upload_path."/$dir/$fields_name/"))             
            mkdir($upload_path."/$dir/$fields_name/");              // field name
        if(!is_dir($upload_path."/$dir/$fields_name/$thumb_dir/"))
            mkdir($upload_path."/$dir/$fields_name/$thumb_dir/");   // thumb name  
 
        if(isset($config['crop']) && $config['crop'] == true) {
          // Make Crop 
          self::cropImage($size[0], $size[1],
            $upload_path."/$dir/$fields_name/".$that->getImage(),
            $upload_path."/$dir/$fields_name/$thumb_dir/".$that->getImage());
        } else {
          // Make Thumb
          $thumbnail = new sfThumbnail($size[0], $size[1]);
          $thumbnail->loadFile($upload_path."/$dir/$fields_name/".$that->getImage()); 
          $thumbnail->save($upload_path."/$dir/$fields_name/$thumb_dir/".$that->getImage(), 'image/png');
        }
      }
    } 
 
  }  
 
  /*
   * delete each thumbnail when you delete binded element
   */
  public static function deleteThumb($values,PropelPDO $con, $class)
  {
    // Variable 
    list($dir, $configs) = self::getDefaultConfig($class);
    $upload_path = sfConfig::get('sf_upload_dir');
 
    if($retVal = call_user_func(array('Base' . $class .'Peer','doDelete'),$values, $con))
 
    foreach($configs as $fields_name => $fields_config) {
 
      $files = self::_getThumb($values, $class, $fields_name);
 
      if($files){     
 
        foreach($files as $file) {
          if(is_file($upload_path."/$dir/$fields_name/".$file)) {
            unlink( $upload_path . "/$dir/$fields_name/".$file );
          }
 
          foreach($fields_config as $config){
            $thumb_dir = $config['thumb_dir'];
            if(is_file($upload_path."/$dir/$fields_name/$thumb_dir/".$file)) {
              unlink( $upload_path . "/$dir/$fields_name/$thumb_dir/".$file );
            }
          }
        }
      }
    }
    return $retVal;
  }
 
  /*
   * retruive all piture
   */ 
  protected  static function _getThumb($values, $class, $fields_name){ 
    // Variable 
    $files       = false;   
    $fields_name = 'get' . ucfirst($fields_name);
 
    if ($values instanceof Criteria) {
      $tmps = call_user_func(array($class.'Peer','doSelect'), $values);
 
      foreach($tmps as $value)
        if($temp_thumb = call_user_func(array($value,$fields_name)) != '')
          $files[] = $temp_thumb;
    } elseif (get_class($values) == $class) {        
 
      if($temp_thumb = call_user_func(array($values,$fields_name))  != '')
        $files[] = $temp_thumb;
 
    } else {
      $tmps = call_user_func(array($classPeer,'retrieveByPKs'),$values);
 
      foreach($tmps as $value)
        if($temp_thumb = call_user_func(array($value,$fields_name)) != '')
          $files[] = $temp_thumb;
    }
    return $files;
  }
 
 
 
  /* 
   * This method thumbnailize image with crop option (center default)
   */
  public static function cropImage($nw, $nh, $source, $dest) { 
      $size = getimagesize($source);
      $len = strlen($source);
      $stype = substr($source,$len-3,3);
      $w = $size[0];
      $h = $size[1]; 
      switch($stype) {
          case 'gif':
            $simg = imagecreatefromgif($source);
          break;
          case 'jpg':
            $simg = imagecreatefromjpeg($source);
          break;
          case 'png':
            $simg = imagecreatefrompng($source);
          break;
      }
      $dimg = imagecreatetruecolor($nw, $nh); 
      $wm = $w/$nw;
      $hm = $h/$nh;
      $h_height = $nh/2;
      $w_height = $nw/2;
      if($w> $h) {
          $adjusted_width = $w / $hm;
          $half_width = $adjusted_width / 2;
          $int_width = $half_width - $w_height;
          imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
      } elseif(($w <$h) || ($w == $h)) {
          $adjusted_height = $h / $wm;
          $half_height = $adjusted_height / 2;
          $int_height = $half_height - $h_height;
          imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
      } else {
          imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
      }
      imagejpeg($dimg,$dest,150);
  }
}
 
by Simon Bonjean on 2009-03-01, tagged propel  sfthumbnail  thumb  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)
{
    $image_dir=dirname($image);
    $image_file=basename($image);
    $thumbnail_dir='';
    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); 
      $thumbnail->loadFile(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$image_file);
      $thumbnail->save(sfConfig::get('sf_upload_dir').'/'.$image_dir.'/'.$thumbnail_dir.$image_file);
    }
    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)
  {
    sfLoader::loadHelpers('Thumbnail');
    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)

Upload Image and generate thumbnails with Admin Generator

With admin generator you can have a field specified to be a uploading file. Then as it is written in the doc, you can wirte in your generator.yml :

      picture:             
        name: Picture
        type: admin_input_file_tag
        upload_dir: picture
        params: include_link=picture include_remove=true

Then the file will be uploaded in /upload/picture directory

But maybe you want to restrict the size of the picture or add different files for different picture sizes.

Then this is an easy way to generate thumbnails in subdirectories of the main upload directory specified.

Just add the following method to your action class and adapt :

action.class.php:

  protected function updateProductFromRequest()
  {
    $product = $this->getRequestParameter('product');
 
    $thumbnails[]=array('dir' => '16x16', 'width' => 16, 'height' => 16);
    $thumbnails[]=array('dir' => '32x32', 'width' => 32, 'height' => 32);
 
    if (!$this->getRequest()->hasErrors() && isset($produit['picture_remove']))
    {
      foreach ($thumbnails as $thumbParam)
      {
        $currentFile = sfConfig::get('sf_upload_dir').'/picture/'.$thumbParam['dir'].'/'.$this->produit->getPhoto();
        if (is_file($currentFile)) unlink($currentFile);
      }
    }
 
    parent::updateProductFromRequest();
 
    if (!$this->getRequest()->hasErrors() && $this->getRequest()->getFileSize('product[picture]'))
    {
      $fileName=$this->product->getPicture();
      foreach ($thumbnails as $thumbParam)
      {
        $thumbnail = new sfThumbnail($thumbParam['width'], $thumbParam['height'],true,false); 
        $thumbnail->loadFile(sfConfig::get('sf_upload_dir')."/product/".$fileName);
        $thumbnail->save(sfConfig::get('sf_upload_dir').'/product/'.$thumbParam['dir'].'/'.$fileName, 'image/jpeg');
      }
    }
  }

As for uploaded files, fenerated thumbnails are not deleted when record is deleted.

by Sylvain PAPET on 2006-10-16, tagged admin  generator  thumbnail 
(6 comments)