Función Thumb
Bueno, ando probando cosas en el blog, y ahora será el coloreado de sintaxis de código. Esta es una funcion que hice hace tiempo y que sirve para redimensionar una imagen proporcionalmente. Su modo de uso es bastante sencillo, consta de 5 parametros, dos de ellos opcionales:
$img - La imagen a redimensionar (string)
$w - El ancho máximo (int)
$h - La altura máxima (int)
$fill - Si la imagen es mas chica, ¿se agranda al tamaño máximo (true, por defecto)? (boolean/opcional)
$save - ¿Guarda la imagen (true) o la muestra en el navegador (false, por defecto)? (boolean/opcional)
Ademas, cuando el 5º parámetro se pone en true (es decir, que la imagen se guarde en lugar de mostrarse), devuelve un arreglo que consiste en el nombre del thumbnail y sus medidas (ancho y alto).
list($thumbnail, $ancho, $alto) = thumb("imagen.jpg", 300, 300, true, true);
<?php
function thumb($img, $w, $h, $fill = true, $save = false) {
if (!extension_loaded('gd') && !extension_loaded('gd2')) {
trigger_error("No dispones de la libreria GD para generar la imagen.", E_USER_WARNING);
return false;
}
$imgInfo = getimagesize($img);
switch ($imgInfo[2]) {
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img); break;
case 3: $im = imagecreatefrompng($img); break;
default: trigger_error('Tipo de imagen no reconocido.', E_USER_WARNING); break;
}
//Esta parte donde se sacan las medidas esta tomada de http://php-hispano.net/archivos/Funciones/170/1
if ($imgInfo[0] <= $w && $imgInfo[1] <= $h && !$fill) {
$nHeight = $imgInfo[1];
$nWidth = $imgInfo[0];
}else{
if ($w/$imgInfo[0] < $h/$imgInfo[1]) {
$nWidth = $w;
$nHeight = $imgInfo[1]*($w/$imgInfo[0]);
}else{
$nWidth = $imgInfo[0]*($h/$imgInfo[1]);
$nHeight = $h;
}
}
$nWidth = round($nWidth);
$nHeight = round($nHeight);
$newImg = imagecreatetruecolor($nWidth, $nHeight);
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
if ($save === true) {
$name = array_shift(explode(".", $img, 2)).".th.".strtolower(array_pop(explode(".", $img)));
if (!file_exists($name)) {
switch ($imgInfo[2]) {
case 1: imagegif($newImg, $name); break;
case 2: imagejpeg($newImg, $name); break;
case 3: imagepng($newImg, $name); break;
default: trigger_error('Imposible mostrar la imagen.', E_USER_WARNING); break;
}
}
return array($name, $nWidth, $nHeight);
}else{
header("Content-type: ". $imgInfo['mime']);
switch ($imgInfo[2]) {
case 1: imagegif($newImg); break;
case 2: imagejpeg($newImg); break;
case 3: imagepng($newImg); break;
default: trigger_error('Imposible mostrar la imagen.', E_USER_WARNING); break;
}
imagedestroy($newImg);
}
}
?>
Antes de ponerla aqui le hice unas modificaciones, espero aun sirva xD



