@Darem0 si señor!

Redimensionar imágenes en CakePHP

Desarrollando una app en CakePHP, me encontré con que necesitaba hacerle resize a un par de imagenes para mostrarlas en el frontend. Es un tema común en cualquier desarrollo y no debería ser tan complicado. Buscando, encontré esta solución que si bien estaba buena, en la versión de CakePHP que estoy usando no servía, asi que la modifiqué un poco y ahora anda. Es un helper, por lo que se puede usar directamente desde el template previamente llamándolo en el controller

El helper solito se encarga de hacerle el resize a las imágenes y guardarlas en el directorio /webroot/image_cache, hay que asegurarse de que ese directorio exista

/app/views/helpers/resizer.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php  
class ResizerHelper extends AppHelper { 
    var $helpers = array('Html'); 
    var $cacheDir = 'image_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) {
        $types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type
        $fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS;
        $url = $fullpath.$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->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file 
        $cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.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, null), $return); 
    } 
}
?>

Entonces, para poder usarlo en el template hay que agregarlo en el controller

1
var $helpers    = array('Html', 'Form', 'Session', 'Resizer');

Y finalmente, en el template

1
<?php echo $this->Resizer->resize($image['url'], 150, 150, true) ?>

Upload de imagenes en CakePHP

Primero que nada, quiero decir que no soy un power developer de CakePHP ni de PHP. De hecho medio que casi no me gusta escribir PHP. Con esto dicho, tiro un pequeño snippet que uso en CakePHP para hacer upload de imágenes en cakephp usando un file input en la vista

Para que entiendan mejor, esto es un admin_add de una news. Una news es como un post de blog que tiene titulo, cuerpo y una imagen asociada. En la tabla solo guardo la URL a la imagen que se hizo upload.

Primero, el snippet de la función que hace el upload. Esto lo pongo directamente en el controller como ultimo metodo, junto con los edit, add, admin_add, view, index, whatever.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function __upload($file_array){
    $file = new File($file_array['tmp_name']);
    $file_base = pathinfo($file_array['name']);;
    $ext = strtolower($file_base['extension']);
    if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'png') {
        $this->Session->setFlash('You may only upload image files.');
        $this->render();
    } else {
        $data = $file->read();
        $file->close();
        $full_path = '/upload_images/'.$file_array['name'];
        $file = new File(WWW_ROOT.$full_path, true);
        $file->write($data);
        $file->close();
         return $full_path;
    }
    return 'Ouch!';
}

Si usas este ejemplo, las imagenes se guardan en wwwroot/upload_images/

Este snippet funciona con cualquier tipo de archivos, no solo con imagenes. Es cuestión de sacarle el check que hago al tipo de extensión del archivo.

Si querés ver como lo uso, vas a tener que entrar al post.. :P

Seguir Leyendo »

Forma rápida de agregar el ultimo tweet a tu blog

<div id="tweet">
<?php
require_once(ABSPATH . 'wp-includes/class-snoopy.php');
$snoopy = new Snoopy;
$snoopy->fetch("http://twitter.com/statuses/user_timeline/[tu-nick].json?count=1");
$twitterdata = json_decode($snoopy->results,true);
?>
<h2><?php echo $twitterdata[0]["text"]; ?></h2>
</div>

Ojo con la parte de [tu-nick]

Via Yoast