Foros del Web » Programando para Internet » PHP »

[APORTE] Librería GD Image Resize

Estas en el tema de [APORTE] Librería GD Image Resize en el foro de PHP en Foros del Web. Hoy andaba necesitando una librería para redimensionar imágenes, busque y busque y no encontré ninguna que me satisficiera. Soy casi un principiante en PHP,esta no ...
  #1 (permalink)  
Antiguo 17/10/2014, 01:44
Avatar de ema_cs_2010  
Fecha de Ingreso: noviembre-2010
Mensajes: 8
Antigüedad: 15 años, 10 meses
Puntos: 0
Información [APORTE] Librería GD Image Resize

Hoy andaba necesitando una librería para redimensionar imágenes, busque y busque y no encontré ninguna que me satisficiera.

Soy casi un principiante en PHP,esta no es mi área xd. Si alguien ve algún error o tiene alguna sugerencia para hacer algo de una mejor forma porfavor comente :D.

__________________________________________________ ________

Es una simple librería para redimensionar/convertir imágenes usando GD.

Soporta:
- Formatos PNG, JPG y GIF.
- Transparencia.
- Imagen PNG indexada (8pbb)
- Transparencia en imágenes de 8bpp

(Para la semana que viene agrego soporte para salida de gif animado)


Código PHP:
<?php

/**
 * GD Image Resize
 * By Destro
 ==============================================================
 
 object new GDimage_resize($ImageFile);
 
 
 * Indica que la salida sera una imagen GIF
 object->out_gif()
 
 
 * Indica que la salida sera una imagen JPG
   - Quality:
      La calidad de la imagen, valores entre 0(mala) y 100(buena) 
 object->out_jpg($Quality=75)
 
 
 * Indica que la salida sera una imagen PNG
  - Quality:
     Compresion de la imagen, valores entre 0(baja) y 9(alta)
  - Filters:
     PNG_NO_FILTER: 0
     PNG_FILTER_NONE: 8
     PNG_FILTER_SUB: 16
     PNG_FILTER_UP: 32
     PNG_FILTER_AVG: 64
     PNG_FILTER_PAETH: 128
     PNG_ALL_FILTERS: 248
  - IndexedColors:
     Define la cantidad de colores para la paleta, valores de 1 a 255 
  - Dither:
     Indica si la imagen debería ser entramada
  - TransColor:
     Define el color que sera transparente, array('r' 'g' 'b')
 object->out_png($Quality=9, $Filters=0, $IndexedColors=0, $Dither=false, $TransColor=false)

 
 * Redimensiona/Convierte una imagen
   - Out_FileName:
      Ruta en la que guardar la imagen, Si no se establece, o su valor es NULL, se mostrará directamente en la salida el flujo de imagen.
   - Width:
      Ancho de la imagen, si es 0 se calcula en proporción a la altura(height)
   - Height:
      Altura de la imagen, si es 0 se calcula en proporción a la anchura(width)
   - Return_resource:
      La imagen no se guarda ni se muestra, se devuelve un recurso imagen.
   - Return:
      Devuelve false si ocurre algún error, de lo contrario true o un recurso imagen si Return_resourc esta en true.
 object->resize($Out_FileName, $width, $height, $return_resource=false);
*/

class GDimage_resize
{
    private 
$imgStream;
    private 
$imgNewWidth;
    private 
$imgNewHeight;
    
    private 
$imgOutName;
    private 
$imgOutType;
    private 
$imgOutQuality;
    private 
$imgOutPNGFilters;
    private 
$imgOutIndex;
    private 
$imgOutIndexedColor;
    private 
$imgOutDither;
    private 
$imgOutTransColor;
    
    public 
$imgSrc;
    public 
$imgWidth;
    public 
$imgHeight;
    public 
$imgType;
    
//public $imgGIFAnim;

    
public function __construct($ImageFile)
    {
        
$imgInfo = @getimagesize($ImageFile);

        if(!
$imgInfo || $imgInfo[2] < 1 || $imgInfo[2] > 3) exit;
        
        
$this->imgStream = file_get_contents($ImageFile);
        
        
$this->imgSrc = imagecreatefromstring($this->imgStream);
        if(
$this->imgSrc == false) exit;
        
        
$this->imgWidth = $imgInfo[0];
        
$this->imgHeight = $imgInfo[1];
        
$this->imgType = $imgInfo[2];
        
        
//if($this->imgType == 1) $this->imgGIFAnim = $this->gifAnim();
    
}
    
    public function 
out_gif()
    {
        
$this->imgOutType = 1;
    }
    
    public function 
out_jpg($Quality=75)
    {
        
$this->imgOutType = 2;
        
$this->imgOutQuality = $Quality;
    }
    
    public function 
out_png($Quality=9, $Filters=0, $IndexedColors=0, $Dither=false, $TransColor=false)
    {
        
$this->imgOutType = 3;
        
$this->imgOutQuality = $Quality;
        
$this->imgOutPNGFilters = $Filters;
        
$this->imgOutIndexedColor = $IndexedColors;
        
$this->imgOutDither = $Dither;
        
$this->imgOutTransColor = $TransColor;
    }
    
    public function 
resize($Out_FileName, $width, $height, $return_resource=false)
    {
        
$this->imgOutName = $Out_FileName;
        
        if(
$width && $height)
        {
            
$this->imgNewWidth = $width;
            
$this->imgNewHeight = $height;
        }
        else if(
$width)
        {
            
$ration = $width/$this->imgWidth;
            
$this->imgNewWidth = $width;
            
$this->imgNewHeight = $this->imgHeight*$ration;
        }
        else if(
$height) {
            
$ration = $height/$this->imgHeight;
            
$this->imgNewHeight = $height;
            
$this->imgNewWidth = $this->imgWidth*$ration;
        }
        else {
            
$this->imgNewWidth = $this->imgWidth;
            
$this->imgNewHeight = $this->imgHeight;
        }

        
/*if($this->imgGIFAnim && $this->imgOutType <= 1)
        {
            echo "no support";
            return false;
        }*/
        
        
return $this->resize_and_convert($return_resource);
    }

    private function 
resize_and_convert($return_resource)
    {
        if(
$this->imgType != 1)
            
$thumb = imagecreatetruecolor($this->imgNewWidth, $this->imgNewHeight);
        else 
$thumb = imagecreate($this->imgNewWidth, $this->imgNewHeight);
        
        if(
$this->imgType == 1) // GIF
        
{
            
$trans_color = imagecolortransparent($this->imgSrc);
            if(
$trans_color >= 0 && $trans_color < imagecolorstotal($this->imgSrc))
            {
                
$trans = imagecolorsforindex($this->imgSrc, $trans_color);
                
$new_trans_color = imagecolorallocate($thumb, $trans['red'], $trans['blue'], $trans['green']);
                
imagefill($thumb, 0, 0, $new_trans_color);
                
imagecolortransparent($thumb, $new_trans_color);
            }
            
imagecopyresized($thumb, $this->imgSrc, 0, 0, 0, 0, $this->imgNewWidth, $this->imgNewHeight, $this->imgWidth, $this->imgHeight);
        }
        else 
// PNG / JPG
        
{    
            if(
$this->imgType == 3) // PNG
            
{
                if(!
$this->imgOutIndexedColor)
                {
                    
imagealphablending($thumb, false);
                    
imagefill($thumb, 0, 0, imagecolorallocatealpha($thumb, 0, 0, 0, 127));
                    
imagesavealpha($thumb, true);
                }
                else if(
is_array($this->imgOutTransColor))
                {
                    
imagefill($thumb, 0, 0,
                    
imagecolorallocate($thumb, $this->imgOutTransColor['r'], $this->imgOutTransColor['g'], $this->imgOutTransColor['b']));
                }
            }
            
            
imagecopyresampled($thumb, $this->imgSrc, 0, 0, 0, 0, $this->imgNewWidth, $this->imgNewHeight, $this->imgWidth, $this->imgHeight);
        }

        if(
$this->imgOutIndexedColor && $this->imgType == 3)
        {
            
imagetruecolortopalette($thumb, $this->imgOutDither, $this->imgOutIndexedColor);
            
            if(
is_array($this->imgOutTransColor))
            {
                
imagecolortransparent($thumb,
                
imagecolorclosest($thumb, $this->imgOutTransColor['r'], $this->imgOutTransColor['g'], $this->imgOutTransColor['b']));
            }
        }

        if(
$return_resource)
            return 
$thumb;
            
        if(
$this->imgOutType) $OutType = $this->imgOutType;
        else 
$OutType = $this->imgType;
        
        if(
$OutType == 1) imagegif($thumb, $this->imgOutName);
        else if(
$OutType == 2) imagejpeg($thumb, $this->imgOutName, $this->imgOutQuality);
        else 
imagepng($thumb, $this->imgOutName, $this->imgOutQuality, $this->imgOutPNGFilters);

        
imagedestroy($thumb);
        return 
true;
    }
}

Ejemplo:
Código PHP:
<?php

require_once "resizer_class.php";
 
 
$imagen = new GDimage_resize("original.png");
if(!
$imagen)
{
    echo 
"Error al cargar la imagen";
    exit;
}

$imagen->out_png();
$resize = $imagen->resize("salida.png", 200, 200);

$imagen->out_gif();
$resize = $imagen->resize("salida.gif", 100, 0);

$imagen->out_jpg(100);
$resize = $imagen->resize("salida.jpg", 0, 300);

echo 
"Imagen redimensionada";

?>

Última edición por ema_cs_2010; 17/10/2014 a las 01:51
  #2 (permalink)  
Antiguo 17/10/2014, 08:46
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 18 años, 5 meses
Puntos: 2534
Respuesta: [APORTE] Librería GD Image Resize

¿Se puede instalar como dependencia de Composer o hay que copiar y pegar?
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 17/10/2014, 13:25
Avatar de ema_cs_2010  
Fecha de Ingreso: noviembre-2010
Mensajes: 8
Antigüedad: 15 años, 10 meses
Puntos: 0
Respuesta: [APORTE] Librería GD Image Resize

Hasta el día de hoy no tenia la menor puta idea de que era Composer jaja
Copiar y Pegar :P

_______________________________________________
Alguien tiene idea porque no me deja editar el thread(tema) ?, mejore par de cosas pero no me deja editar para actualizar u.u


@EDIT
Buscando info sobre Composer me encontré con packagist.org. Encontré mas librerías útiles en 1 minuto que todo el día de ayer googleando e.e.

Última edición por ema_cs_2010; 17/10/2014 a las 13:35

Etiquetas: image, resize
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:48.