Topic: mai più thumbnails (caching furbo delle miniature delle immagini)
avevo bisogno di crearmi un component che, durante il salvataggio di una immagine sul server, mi realizzasse X thumbnails di diverse dimensioni, da utilizzare in base alla pagina in cui le volevo visualizzare.
mi sono imbattuto per caso in questo helper, che risolve in modo decisamente più furbo il mio problema:
http://bakery.cakephp.org/articles/view ize-helper
in sostanza, è un helper che crea dinamicamente le thumbnails delle dimensioni che gli vengono passate quando lo si richiama, e le salva automaticamente in una directory in modo da poterle ripescare in un secondo momento, in modo tale da non doverle ricreare ogni volta.
nel mio caso ho dovuto modificare leggermente il codice, affinchè mi creasse tante directory quanti sono i formati che mi servono, in cui piazzare dentro le relative miniature (es. cache/320x200/immagine1.jpg, cache/160x100/immagine1.jpg ecc.)
questo è l'helper come l'ho modificato io:
class ImageHelper extends Helper {
var $helpers = array('Html');
var $cacheDir = 'cache'; // relative to IMAGES_URL path
/**
* Automatically resizes an image and returns formatted IMG tag
*
* @param string $path Path to the image file, relative to the webroot/img/ directory.
* @param integer $width Image of returned image
* @param integer $height Height of returned image
* @param boolean $aspect Maintain aspect ratio (default: true)
* @param array $htmlAttributes Array of HTML attributes.
* @param boolean $return Wheter this method should return a value or output it. This overrides AUTO_OUTPUT.
* @return mixed Either string or echos the value, depends on AUTO_OUTPUT and $return.
* @access public
*/
function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
$dir = "{$width}x{$height}";
$types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type
$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this->themeWeb.IMAGES_URL;
if(!is_dir($fullpath.$this->cacheDir.DS.$dir))
{
$percorso = str_replace('/', '\\', $fullpath.$this->cacheDir.DS.$dir);
mkdir($percorso);
}
$url = $path;
if (!($size = getimagesize($url)))
return; // image doesn't exist
if ($aspect) { // adjust to aspect.
if (($size[1]/$height) > ($size[0]/$width)) // $size[0]:width, [1]:height, [2]:type
$width = ceil(($size[0]/$size[1]) * $height);
else
$height = ceil($width / ($size[0]/$size[1]));
}
$relfile = $this->webroot.$this->themeWeb.IMAGES_URL.$this->cacheDir.'/'.$dir.'/'.basename($path); // relative file
$cachefile = $fullpath.$this->cacheDir.DS.$dir.DS.basename($path); // location on server
if (file_exists($cachefile)) {
$csize = getimagesize($cachefile);
$cached = ($csize[0] == $width && $csize[1] == $height); // image is cached
if (@filemtime($cachefile) < @filemtime($url)) // check if up to date
$cached = false;
} else {
$cached = false;
}
if (!$cached) {
$resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
} else {
$resize = false;
}
if ($resize) {
$image = call_user_func('imagecreatefrom'.$types[$size[2]], $url);
if (function_exists("imagecreatetruecolor") && ($temp = imagecreatetruecolor ($width, $height))) {
imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
} else {
$temp = imagecreate ($width, $height);
imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
}
call_user_func("image".$types[$size[2]], $temp, $cachefile);
imagedestroy ($image);
imagedestroy ($temp);
}
return $this->output(sprintf($this->Html->tags['image'], $relfile, $this->Html->_parseAttributes($htmlAttributes, null, '', ' ')), $return);
}
}per richiamare l'helper bisogna usare un codice tipo questo: $image->resize($img_path, $thumb_size_box['width'], $thumb_size_box['height'], true);
$thumb_size_box['width'] e $thumb_size_box['height'] sono due variabili che mi sono messo io da qualche parte, se preferite potete ovviamente utilizzare dei valori hardcoded. il true finale serve per dirgli di mantenere le proporzioni, se lo settate a false crea l'immagine con esattamente le dimensioni che gli specificate (quindi distorta ovviamente)
N.B.: nell'ultima riga c'è un _parseAttributes, se usate cakephp 1.1 invece dell'1.2 dovete usare parseHtmlOptions