Hace unos años creé una clase PHP para crear thumbnails de imágenes porque la necesitaba para un proyecto, necesitaba ciertas cosas de dicha clase que no encontraba en otras muchas que encontré por la red, por lo que me propuse crear la mía propia ajustándola a las necesidades que tenía en ese momento. Hoy, después de algunos ajustes y arreglos para perfeccionarla he decidido compartirla para que quien la necesite pueda hacer uso de ella.
Posibilidades de esta clase:
- Capacidad de trabajar con los principales formatos de imágenes (jpg, png y gif).
- Capacidad para redimensionar las imágenes por ancho o alto al valor deseado sin que pierda sus proporciones.
- Capacidad de recortar la imagen a los valores deseados sin que pierda la proporción original y escogiendo la posición del del recorte.
- Capacidad de guardar la imagen manipulada en el servidor.
- Capacidad de mostrar la imagen directamente en el navegador.
- Capacidad de mantener la transparencia de imágenes PNG o GIF.
Esta clase necesita de la librería GD instalada en el servidor (incluida en PHP a partir de la versión 4.3)
Clase PHP para crear thumbnails de imágenes
class Thumb {
private $image;
private $type;
private $mime;
private $width;
private $height;
public function loadImage($name) {
$info = getimagesize($name);
$this->width = $info[0];
$this->height = $info[1];
$this->type = $info[2];
$this->mime = $info['mime'];
switch($this->type){
case IMAGETYPE_JPEG:
$this->image = imagecreatefromjpeg($name);
break;
case IMAGETYPE_GIF:
$this->image = imagecreatefromgif($name);
break;
case IMAGETYPE_PNG:
$this->image = imagecreatefrompng($name);
break;
default:
trigger_error('No se puede crear un thumbnail con el tipo de imagen especificada', E_USER_ERROR);
}
}
public function save($name, $quality = 100, $type = false) {
$type = ($type) ? $type : $this->type;
switch($type){
case IMAGETYPE_JPEG:
imagejpeg($this->image, $name . image_type_to_extension($type), $quality);
break;
case IMAGETYPE_GIF:
imagegif($this->image, $name . image_type_to_extension($type));
break;
case IMAGETYPE_PNG:
$pngquality = floor($quality / 100 * 9);
imagepng($this->image, $name . image_type_to_extension($type), $pngquality);
break;
default:
trigger_error('No se ha especificado un formato de imagen correcto', E_USER_ERROR);
}
}
public function show($type = false, $base64 = false) {
$type = ($type) ? $type : $this->type;
if($base64) ob_start();
switch($type){
case IMAGETYPE_JPEG:
imagejpeg($this->image);
break;
case IMAGETYPE_GIF:
imagegif($this->image);
break;
case IMAGETYPE_PNG:
$this->prepareImage($this->image);
imagepng($this->image);
break;
default:
trigger_error('No se ha especificado un formato de imagen correcto', E_USER_ERROR);
exit;
}
if($base64) {
$data = ob_get_contents();
ob_end_clean ();
return 'data:' . $this->mime . ';base64,' . base64_encode($data);
}
}
public function resize($value, $prop){
$prop_value = ($prop == 'width') ? $this->width : $this->height;
$prop_versus = ($prop == 'width') ? $this->height : $this->width;
$pcent = $value / $prop_value;
$value_versus = $prop_versus * $pcent;
$image = ($prop == 'width') ? imagecreatetruecolor($value, $value_versus) : imagecreatetruecolor($value_versus, $value);
if($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG) $this->prepareImage($image);
switch($prop){
case 'width':
imagecopyresampled($image, $this->image, 0, 0, 0, 0, $value, $value_versus, $this->width, $this->height);
break;
default:
imagecopyresampled($image, $this->image, 0, 0, 0, 0, $value_versus, $value, $this->width, $this->height);
}
$this->width = imagesx($image);
$this->height = imagesy($image);
$this->image = $image;
}
public function crop($cwidth, $cheight, $pos = 'center') {
$pcent = min($this->width / $cwidth, $this->height / $cheight);
$bigw = (int) ($pcent * $cwidth);
$bigh = (int) ($pcent * $cheight);
$image = imagecreatetruecolor($cwidth, $cheight);
if($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG) $this->prepareImage($image);
switch($pos){
case 'left':
imagecopyresampled($image, $this->image, 0, 0, 0, abs(($this->height - $bigh) / 2), $cwidth, $cheight, $bigw, $bigh);
break;
case 'right':
imagecopyresampled($image, $this->image, 0, 0, $this->width - $bigw, abs(($this->height - $bigh) / 2), $cwidth, $cheight, $bigw, $bigh);
break;
case 'top':
imagecopyresampled($image, $this->image, 0, 0, abs(($this->width - $bigw) / 2), 0, $cwidth, $cheight, $bigw, $bigh);
break;
case 'bottom':
imagecopyresampled($image, $this->image, 0, 0, abs(($this->width - $bigw) / 2), $this->height - $bigh, $cwidth, $cheight, $bigw, $bigh);
break;
default:
imagecopyresampled($image, $this->image, 0, 0, abs(($bigw - $this->width) / 2), abs(($bigh - $this->height) / 2), $cwidth, $cheight, $bigw, $bigh);
}
$this->width = $cwidth;
$this->height = $cheight;
$this->image = $image;
}
private function prepareImage($image){
switch($this->type){
case IMAGETYPE_GIF:
$background = imagecolorallocate($image, 0, 0, 0);
imagecolortransparent($image, $background);
break;
case IMAGETYPE_PNG:
imagealphablending($image, FALSE);
imagesavealpha($image, TRUE);
break;
}
}
}
Métodos públicos de la clase
|
|
$name
|
Ruta de la imagen
|
|
$name
|
Ruta donde se guardará la imagen
|
$quality
|
Calidad de la imagen con un valor de 0 a 100
|
$type
|
Tipo de imagen definido por una constante IMAGETYPE_XXX (IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF), si no se envía se guarda la imagen en su formato original
|
|
$type
|
Tipo de imagen definido por una constante IMAGETYPE_XXX (IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF), si no se envía se muestra la imagen en su formato original
|
$base64 |
Especifica si el flujo de la imagen debe imprimirse directamente en la página o si se desea que devuelva una representación en base64 de la misma para usarla como parámetro «src» de un elemento «img».
|
|
$value
|
El valor de ancho o alto al que se desea redimensionar la imagen
|
$reference
|
String que define si la imagen se redimensionará tomando como referencia el ancho o el alto (valores posibles: ‘width’ o ‘height’)
|
|
$width
|
El valor de ancho del thumbnail
|
$height
|
El valor de alto del thumbnail
|
$position
|
La posición de donde se tomará el thumbnail (valores posibles: ‘top’, ‘right’, ‘bottom’, ‘left’ o ‘center’)
|
Demo en funcionamiento
Ver demo
Descarga de ficheros
Descarga los ficheros de ejemplo de la Clase PHP para crear thumbnails de imágenes.





(
5 votos, promedio:
4,00 de 5)
Muchas gracias! me sirvio de mucho.
Me alegro Francisco. ¡Un saludo!
Excelente codigo amigo! realmente sacas de apuro a muchos de nosotros…una sugerencia, crees poder ser flexible en el resize, es decir colocar los valores de alto y ancho sin ser proporcional…
Hola Azael:
Eso es justamente lo que hace el método crop:
Puedes ver su uso y el resultado en la página de demostración.
Un saludo y me alegra que te haya servido de ayuda.
Excelente codigo! Muchas gracias por compartirlo. Saludos
Me alegro de que te haya servido de ayuda, Federico.
Un saludo.
si…muy bueno el código acaba con dolores de cabeza…jejejeje muy buen aporte!