Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "sfthumbnail"

admin Generator and Thumnail generation in file uploads with symfony 1.2

Hello to the desperate,

As you might have probably already mentioned, the old way, how to produce thumbnails stopped working. This is because of the brand new admin generator, using an all new model based on forms, which doesn't support the old methods.

this is the new way, how to get it working again:

put this into your generator.yml file (take care for the correct identation, do not use tabs!!):

      edit:
        title: Photo uploads 
        fields:
          foto:
            type:       admin_input_file_tag
            upload_dir: /uploads/pictures/
            params:     include_link=/uploads/pictures/ include_remove=true
 

and then enhance the file lib/form/YourclassForm.php with the following method:

  protected function processUploadedFile($field, $filename = null, $values = null) {
    // first of all do what this is supposed to do
    $fn = parent::processUploadedFile($field, $filename, $values);
    // and now we can finally start doing additional stuff after the upload *hurra*
    if ($fn != "") {
        // if there is a file, that has been saved
        // multidimensional array that defines the sub-directories to store the thumbnails in
        $thumbnails[]=array('dir' => '90x90', 'width' => 90, 'height' => 90);
        $thumbnails[]=array('dir' => '200x200', 'width' => 200, 'height' => 200);
 
        foreach ($thumbnails as $thumbParam)
        {
          $currentFile = sfConfig::get('sf_upload_dir').'/pictures/'.$thumbParam['dir'].'/'. $fn;
          if (is_file($currentFile)) unlink($currentFile);
        }
        foreach ($thumbnails as $thumbParam)
        {
            $thumbnail = new sfThumbnail($thumbParam['width'], $thumbParam['height'],true,false); 
            $thumbnail->loadFile(sfConfig::get('sf_upload_dir')."/pictures/".$fn);
            $thumbnail->save(sfConfig::get('sf_upload_dir').'/pictures/'.$thumbParam['dir'].'/'.$fn, 'image/jpeg');
        }
    }
    // do not forget to return the value of the parent-function, otherwise it stops working
    return $fn;
  }  
 

Hope, you can use that snippet!

lg Christoph

by Christoph Christ on 2009-05-07, tagged admin  file  generator  sfthumbnail  symfony  uploads 
(2 comments)

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 

unsharp mask for sfThumbnail plugin

I modified some found code (http://vikjavev.no/computing/ump.php?id=35) to add a sharpening feature to sfThumbnail.

Simply add this code to the sfThumbnail class:

  /**
   * Unsharp Mask for PHP
   * Unsharp mask algorithm by Torstein Hønsi
   * Please leave this notice.
   * @author     Torstein Hønsi <thoensi@netcom.no>
   * @author     Modified for use with Symfony by Dave Furfero <furf@furf.com>
   * @version    2.0, 2003-06
   *
   * WARNING! Due to a known bug in PHP 4.3.2 this script is not working
   * well in this version. The sharpened images get too dark. The bug is
   * fixed in version 4.3.3. 
   *
   * From version 2 (July 17 2006) the script uses the imageconvolution
   * function in PHP version >= 5.1, which improves the performance
   * considerably. 
   * 
   * Unsharp masking is a traditional darkroom technique that has proven
   * very suitable for digital imaging. The principle of unsharp masking
   * is to create a blurred copy of the image and compare it to the
   * underlying original. The difference in colour values between the
   * two images is greatest for the pixels near sharp edges. When this
   * difference is subtracted from the original image, the edges will be 
   * accentuated. 
   *
   * Amount simply says how much of the effect you want. 100 is
   * 'normal'
   *
   * Radius is the radius of the blurring circle of the mask.
   *
   * Threshold is the least difference in colour values that is allowed
   * between the original and the mask. In practice this means that
   * low-contrast areas of the picture are left unrendered whereas edges
   * are treated normally. This is good for pictures of e.g. skin or
   * blue skies. 
   *
   * Any suggenstions for improvement of the algorithm, expecially
   * regarding the speed and the roundoff errors in the Gaussian blur
   * process, are welcome. 
   * 
   * @param int amount (0-500)
   * @param float radius (0-50)
   * @param int threshold (0-255)
   * @return void
   * @access public
   */
  public function unsharpMask ($amount, $radius, $threshold)
  {
    // Attempt to calibrate the parameters to Photoshop:
    $amount    = min($amount, 500) * 0.016;
    $radius    = min($radius, 50) * 2;
    $radius    = abs(round($radius)); // Only integers make sense
    $threshold = min($threshold, 255);
 
    if ($amount == 0 || $radius == 0) {
      return;
    }
 
    $w = $this->getThumbWidth();
    $h = $this->getThumbHeight();
 
    $imgCanvas  = imagecreatetruecolor($w, $h);
    $imgCanvas2 = imagecreatetruecolor($w, $h);
    $imgBlur    = imagecreatetruecolor($w, $h);
    $imgBlur2   = imagecreatetruecolor($w, $h);
 
    imagecopy($imgCanvas,  $this->thumb, 0, 0, 0, 0, $w, $h);
    imagecopy($imgCanvas2, $this->thumb, 0, 0, 0, 0, $w, $h);
 
    // Gaussian blur matrix:
    //  1  2  1
    //  2  4  2
    //  1  2  1
 
    imagecopy($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h); // background
 
    for ($i = 0; $i < $radius; $i++)  {
 
      if (function_exists('imageconvolution')) { // PHP >= 5.1
        $matrix = array(
          array(1, 2, 1),
          array(2, 4, 2),
          array(1, 2, 1)
        );
        imageconvolution($imgCanvas, $matrix, 16, 0);
      } else {
 
        // Move copies of the image around one pixel at the time
        // and merge them with weight according to the matrix.
        // The same matrix is simply repeated for higher radii.      
        imagecopy($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1);
        imagecopymerge($imgBlur, $imgCanvas, 1, 1, 0, 0, $w, $h, 50);
        imagecopymerge($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h, 33.33333); 
        imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 1, $w, $h - 1, 25);
        imagecopymerge($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h, 33.33333); 
        imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 0, $w, $h, 25);
        imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 1, $w, $h - 1, 20 );
        imagecopymerge($imgBlur, $imgCanvas, 0, 1, 0, 0, $w, $h, 16.666667);
        imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h, 50);
        imagecopy($imgCanvas, $imgBlur, 0, 0, 0, 0, $w, $h);
 
        // During the loop above the blurred copy darkens,
        // possibly due to a roundoff error. Therefore the sharp
        // picture has to go through the same loop to produce a
        // similar image for comparison. This is not a good
        // thing, as processing time increases heavily.
        imagecopy($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 20 );
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 16.666667);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
        imagecopy($imgCanvas2, $imgBlur2, 0, 0, 0, 0, $w, $h);
      }
    }
 
    // Calculate the difference between the blurred pixels
    // and the original and set the pixels
    for ($x = 0; $x < $w; $x++)  {
      for ($y = 0; $y < $h; $y++)  {
 
        $rgbOrig = imageColorAt($imgCanvas2, $x, $y);
        $rOrig = (($rgbOrig >> 16) & 0xFF);
        $gOrig = (($rgbOrig >> 8) & 0xFF);
        $bOrig = ($rgbOrig & 0xFF);
 
        $rgbBlur = imageColorAt($imgCanvas, $x, $y);
        $rBlur = (($rgbBlur >> 16) & 0xFF);
        $gBlur = (($rgbBlur >> 8) & 0xFF);
        $bBlur = ($rgbBlur & 0xFF);
 
        // When the masked pixels differ less from the original
        // than the threshold specifies, they are set to their original value.
        $rNew = (abs($rOrig - $rBlur) >= $threshold)
          ? max(0, min(255, ($amount * ($rOrig - $rBlur)) + $rOrig))
          : $rOrig;
        $gNew = (abs($gOrig - $gBlur) >= $threshold)
          ? max(0, min(255, ($amount * ($gOrig - $gBlur)) + $gOrig))
          : $gOrig;
        $bNew = (abs($bOrig - $bBlur) >= $threshold)
          ? max(0, min(255, ($amount * ($bOrig - $bBlur)) + $bOrig))
          : $bOrig;
 
        if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) {
          $pixCol = imageColorAllocate($this->thumb, $rNew, $gNew, $bNew);
          imageSetPixel($this->thumb, $x, $y, $pixCol);
        }
      }
    }
  }

Then call it like this from your script:

$thumb = new sfThumbnail(160, 120);
$thumb->loadFile($original_img);
$thumb->unsharpMask(40, 0.5, 3);
$thumb->save($img_path, 'image/png');

The three parameters are amount (degree of sharpening from 0-500), radius (pixel radius of blur, from 0-50), and threshold (degree of difference between original and blur, from 0-255). Read the included comments for more info.

It could probably use some better validation and error checking, but it's worked flawlessly for me so far.

by dave furf on 2006-08-31, tagged plugin  sfthumbnail