Foros del Web » Programando para Internet » PHP »

Redimencionar imagenes

Estas en el tema de Redimencionar imagenes en el foro de PHP en Foros del Web. Alguien tiene alguna solución a redimencionar imagenes?? Creo que ha habido problemas, pues consegui un codigo para redimensionar la imagen pero me doy cuenta que ...
  #1 (permalink)  
Antiguo 29/11/2006, 16:10
 
Fecha de Ingreso: diciembre-2003
Ubicación: Campehce, Mexico
Mensajes: 325
Antigüedad: 20 años, 4 meses
Puntos: 0
Redimencionar imagenes

Alguien tiene alguna solución a redimencionar imagenes?? Creo que ha habido problemas, pues consegui un codigo para redimensionar la imagen pero me doy cuenta que realmente no crea una imagen más pequeña y le baja de tamaño sino que solo la hace mas chica ... Igual lei en algunos comentarios de blogs de que ya no funciona o algo asi.

Agradeceria si alguien pudiera resolver mi duda.

Gracias
  #2 (permalink)  
Antiguo 29/11/2006, 17:46
Avatar de mauled  
Fecha de Ingreso: marzo-2005
Ubicación: Cd. de México.
Mensajes: 3.001
Antigüedad: 19 años, 1 mes
Puntos: 33
Lo que puedes hacer es utilizar imagemagick para "achicar" las imágenes.

Saludillos.
  #3 (permalink)  
Antiguo 29/11/2006, 19:47
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
No sé que código usastes .. tal vez sólo ajustabas el alto/ancho en el tag HTML de imagen: <img src= .....>

Lo que debes es generar una imagen nueva desde la original .. un "thumbnail" (busca en las FAQ's o en este foro .. veras muchos ejemplos).

En PHP es más común que puedas disponer de las librerías GD: www.php.net/gd

Revisa tu instalación de PHP y verifica (haciendo un phpinfo()) que tengas esas extensiones instaladas.

De todas formas .. si quieres probar:
http://phpthumb.sourceforge.net/

Esta classe puede trabajar con GD o ImageMagick según lo que tengas instalado (extensiones/librerias).

Un saludo,
__________________
Por motivos personales ya no puedo estar con Uds. Fue grato haber compartido todos estos años. Igualmente los seguiré leyendo.
  #4 (permalink)  
Antiguo 14/01/2007, 16:50
 
Fecha de Ingreso: enero-2006
Ubicación: Valencia
Mensajes: 96
Antigüedad: 18 años, 3 meses
Puntos: 1
Re: Redimencionar imagenes

Yo tengo un codigo que vi por la red para reducir el tamaño pero tengo un problema al crear imágenes algo grandes. El tema es que para crear imágenes de 120 px o 250 px de ancho no hay problemas pero al crear una de 800 px no crea siembre la imágen reducida.
Los archivos origen suelen ser de 3 MegaPix mas o menos y no se a que se puede deber este problema, no creo q sea potencia del pc ya que mi pc tira bien.

Os pongo mi código, a diferencia del original en este busca la imagen original en un subdirectorio, y crea los thumbs en otros directorios

La llamada es la siguiente
Código PHP:
echo "<img src='redimensionar.php?directorio=$directorio&imagen=$archivo&tamano=800' width=70 height=70><br>800px"
Y el contenido de redimensionar.php
Código PHP:
<?php  
$directorio
="img/".basename($_GET['directorio']);  
$nombre1=basename($_GET['imagen']);  
$nombre=$directorio."/".basename($_GET['imagen']);  
$tamano=basename($_GET['tamano']);  
$anchura=$tamano;  
$hmax=$tamano;  
$datos getimagesize("$nombre");  
//echo "----$directorio/$nombre---";
if($datos[2]==1){$img = @imagecreatefromgif($nombre);}  
if(
$datos[2]==2){$img = @imagecreatefromjpeg($nombre);}  
if(
$datos[2]==3){$img = @imagecreatefrompng($nombre);}  
$ratio = ($datos[0] / $anchura);  
$altura = ($datos[1] / $ratio);  
if(
$altura>$hmax){$anchura2=$hmax*$anchura/$altura;$altura=$hmax;$anchura=$anchura2;}  
$thumb imagecreatetruecolor($anchura,$altura);  
imagecopyresampled($thumb$img0000$anchura$altura$datos[0], $datos[1]);  
$dest="$directorio/$tamano/$nombre1";
$dirdest="$directorio/$tamano/";
echo 
"$dirdest";
if (!
file_exists($dirdest))
           
mkdir($dirdest0777);

if(
$datos[2]==1){header("Content-type: image/gif"); imagegif($thumb); imagejpeg($thumb,$dest,80);}  
if(
$datos[2]==2){header("Content-type: image/jpeg");imagejpeg($thumb);imagejpeg($thumb,$dest,70);}  
if(
$datos[2]==3){header("Content-type: image/png"); imagepng($thumb); imagejpeg($thumb,$dest,80); }  
imagedestroy($thumb);
?>
  #5 (permalink)  
Antiguo 23/01/2007, 12:31
Avatar de CieloEterno  
Fecha de Ingreso: marzo-2006
Ubicación: México
Mensajes: 52
Antigüedad: 18 años, 1 mes
Puntos: 0
Busqueda Redimencionar imagenes

Hola:

Estoy probando mi codigo para hacer más pequeñas las imágenes, pero no he podido encontrar el error

Código PHP:
function redimensionar($imagen,$type,$route,$crmname) {
$ThumbWidth 100;
print 
" ruta $route/$crmname";
    if(
$type == "image/pjpeg" || $type == "image/jpeg"){
print 
"<br>JPEG";
        
$new_img imagecreatefromjpeg($imagen);
    }elseif(
$type == "image/x-png" || $type == "image/png"){
print 
"<br>PNG";
        
$new_img imagecreatefrompng($imagen);
    }elseif(
$type == "image/gif"){
print 
"<br>GIF";
        
$new_img imagecreatefromgif($imagen);
    }elseif(
$type == "image/jpg"){
print 
"<br>JPG";
        
$new_img imagecreatefromjpeg($imagen);
    }

    list(
$width$height) = getimagesize($imagen);
    
$imgratio=$width/$height;

print 
"<br> ancho $width - ";    
print 
" altura $width";    

    if (
$imgratio>1){
        
$newwidth $ThumbWidth;
        
$newheight $ThumbWidth/$imgratio;
    }else{
        
$newheight $ThumbWidth;
        
$newwidth $ThumbWidth*$imgratio;
    }

print 
"<br> nuevo ancho $newwidth - ";
print 
"nuevo altura $newheight";

    if (
function_exists(imagecreatetruecolor)){
        
$resized_img imagecreatetruecolor($newwidth,$newheight);
    }else{
        die(
"Error: Please make sure you have GD library ver 2+");
    }

    
imagecopyresized($resized_img$new_img0000$newwidth$newheight$width$height);


    
ImageJpeg ($resized_img,"$route$crmname");

    
ImageDestroy ($resized_img);
    
ImageDestroy ($new_img);

Llamo a mi función bien, pues entra correctamente y tomar todos mis datos.
Pero la imagen no cambia en lo absoluto, quiero que la pequeña reemplace a la grande.

imagenes/3/mi_imagen_a_hacer_pequeña.gif (grande)
imagenes/3/mi_imagen_pequeña_con_el_mismo_nombre_que la grande.gif pequeña)

Alguien tiene alguna idea, o nota el error en mi codigo?
__________________
Aquel que no tiene nada por lo cual morir, no tiene nada por que vivir
  #6 (permalink)  
Antiguo 23/01/2007, 13:10
Avatar de deet  
Fecha de Ingreso: mayo-2005
Ubicación: Córdoba - Argentina
Mensajes: 269
Antigüedad: 19 años
Puntos: 1
Re: Redimencionar imagenes

yo siempre uso esta clase que utiliza GD y me va muy bien:

Código PHP:
<?
/**
* Crea una imagen nueva de un ancho y alto de terminado a partir de una imagen dada
*
*/
class CropImage {

    var 
$file;

    
    
/**
    * Constrructor de la clase
    *
    * @param string $file Nombre completo del fichero de imagen incluida la ruta al lugar temporal de existencia
    * @param string $origname Nombre original del fichero
    * @param string $targetPath Ruta completa donde será grabado el fichero
    * @param string $saveName Nombre del fichero con el que será grabado el archivo generado 
    * @param integer $newWidth Nuevo ancho del fichero
    * @param integer $newHeight Nuevo alto del fichero 
    * @param string $saveNameThumb Nombre del fichero thumb con el que será grabado el archivo generado
    * @param string $pathThumb Ruta completa donde será grabado el fichero thumb
    */
    
function CropImage($pathFile,$file$origname$saveName$targetPath$newWidth$newHeight,$saveNameThumb,$pathThumb,$pathSinMarca) {
        
        
$this->file $pathFile.$file;
        
$this->origname $origname;
        
$this->targName $saveName;
        
$this->targetPath $targetPath;
        
$this->targetPath1 $pathSinMarca;
        
$this->nw $newWidth;
        
$this->nh $newHeight;
        
$this->targNameThumb $saveNameThumb;
        
$this->targetPathThumb $pathThumb;
        
        
//Determinar el tipo de archivo en base a u extensión
    
if (!isset($type)) 
    { 
        
$ext explode('.'$origname); 
        
$ext $ext[count($ext)-1];
 
        switch(
strtolower($ext)) 
        { 
            case 
'jpg':
              
$this->type 'jpg'
            break; 
            case 
'jpeg':   
              
$this->type 'jpg'
            break; 
                
            default : 
              
$this->type strtolower($ext); 
            break; 
        } 
    }
        
//Crear la imagen de acuerdo al tipo de archivo de imagen
        
$this->im2 imagecreatetruecolor($this->nw$this->nh);
        
$this->im3 imagecreatetruecolor($this->nw$this->nh);
        switch (
$this->type)
    { 
      case 
'jpg':
        
$this->tmpImage = @imagecreatefromjpeg($this->file);     
        
$this->tmpImage1 = @imagecreatefromjpeg($this->file);     
      break; 
  
      case 
'gif'
          
$this->tmpImage = @imagecreatefromgif($this->file);    
          
$this->tmpImage1 = @imagecreatefromgif($this->file);     
      break; 
       
      case 
'png':
          
$this->tmpImage = @imagecreatefrompng($this->file);  
          
$this->tmpImage1 = @imagecreatefrompng($this->file);   
      break; 
      
    }
        
    
$this->ow  imagesx ($this->tmpImage);    // Original image width 
    
$this->oh  imagesy ($this->tmpImage);    // Original image height
    
    
}

    
    
/**
    * Crea la imagen de salida de acuerdo a un ancho, y alto
    *
    */
    
function outPutImage() {
        
imagecopyresampled($this->im2$this->tmpImage0000$this->nw$this->nh$this->ow$this->oh);    
        
imagecopyresampled($this->im3$this->tmpImage10000$this->nw$this->nh$this->ow$this->oh);
        
$mark=imagecreatefrompng("images/logoWatermark.png");
        
imagecopy($this->im2,$mark,(465-150)/2,(310-99)/2,0,0,150,99);
        
$this->saveImage();
    }
    
    
    
/**
    * Escribe la imagen físicamente
    *
    * @param integer $imagen Puntero a la imagen creada
    */
    
function saveImage() {
    
     switch (
$this->type
     { 
        case 
'jpg':
             
imagejpeg($this->im2$this->targetPath $this->targName100);
             
imagejpeg($this->im3$this->targetPath1 $this->targName100);
      break; 
      
      case 
'gif'
          
imagegif($this->im2$this->targetPath $this->targName);
          
imagegif($this->im3$this->targetPath1 $this->targName);
      break; 
      
      case 
'png'
             
imagepng($this->im2$this->targetPath $this->targName);
             
imagepng($this->im3$this->targetPath1 $this->targName);
      break;
      
     } 

    
imagedestroy($this->im2); 
    
imagedestroy($this->im3); 
        
    }

    function 
thumbnail(){
        
$file_orig=$this->file;
        
$file_dest=$this->targNameThumb;
        
//Dimensions
        
$outWidth=206$outHeight=131;
        
//Do it
        
switch ($this->type
         { 
            case 
'jpg':
                
$imgSrc=imagecreatefromjpeg($file_orig);
          break; 
          
          case 
'gif'
                
$imgSrc=imagecreatefromgif($file_orig);
          break; 
          
          case 
'png'
                
$imgSrc=imagecreatefrompng($file_orig);
          break;
          
         } 
        
$srcWidth=imagesx($imgSrc);
        
$srcHeight=imagesy($imgSrc);
        
//Make thumbnails
        
$imgOut=imagecreatetruecolor($outWidth,$outHeight);
        
imagerectangle($imgOut,0,0,$outWidth,$outHeight,imagecolorallocate($imgOut,0,0,0));
        
//Copy them proportionatly
        
$dx=0$dy=0$dw=$outWidth$dh=$outHeight;
        if (
$outWidth*$srcHeight!=$outHeight*$srcWidth) { //Non-proportional, cut-off
            //Which dimensions is larger
            
if ($srcWidth>$srcHeight) { //Empty space on top and bottom
                
$dw=$outWidth;
                
$dh=($dw*$srcHeight)/$srcWidth;
                
$dy=($outHeight-$dh)/2;
            }else { 
//Empty space on left and right
                
$dh=$outHeight;
                
$dw=($dh*$srcWidth)/$srcHeight;
                
$dx=($outWidth-$dw)/2;
            }
        }
        
imagecopyresampled($imgOut,$imgSrc,$dx,$dy,0,0,
        
$dw,$dh,$srcWidth,$srcHeight);//imagecopyresized for lower quality
        //Create the thumbnail and destroy everything else
        //$markThumb=imagecreatefrompng("images/logoWatermarkThumb.png"); 
        //imagecopy($imgOut,$markThumb,($outWidth-102)/2,($outHeight-68)/2,0,0,102,68);
        
switch ($this->type
        { 
        case 
'jpg':
            
imagejpeg($imgOut$this->targetPathThumb $this->targNameThumb100);
        break; 
        
        case 
'gif'
            
imagegif($imgOut$this->targetPathThumb $this->targNameThumb);
        break; 
        
        case 
'png'
            
imagepng($imgOut$this->targetPathThumb $this->targNameThumb);
        break;
        
        } 
        
imagedestroy($imgSrc);
        
imagedestroy($imgOut);
    }        
    
}
?>
Código PHP:
include("cls.CropImage.php");
    
$path="../ruta/del/original/";
    
$file=$image;//nombre tomado de $_FILES
    
$file_orig=$image;//nombre tomado de $_FILES
    
$tamanyo=getimagesize($path.$file);
        
//en este caso tengo un ancho fijo para lo cual hago proporcional la altura
        //pero se pueden poner los valores que quieran
    
$ancho=465;
    
$alto=($tamanyo[1]*465)/$tamanyo[0];
        
//como verán en la próxima línea tengo tres directorios diferentes
        //eso es porque necesitaba crear tres tipos de fotos mas la original
        //una es tamaño medio, la otra tamaño medio pero con marca de agua
        //y la última de tamaño pequeño (thumbnail)
    
$new_image= new CropImage($path,$file$file$file"../fotos/media/"$ancho."px"$alto."px",$file,"../fotos/thumb/","../fotos/media1/");
       
//esto me guarda la imágenes media
    
$new_image->outPutImage();
        
//esto me crea los thumbnails
    
$new_image->thumbnail(); 
esta clase me la han pasado no me acuerdo quién, yo le realicé las modificaciones de foto con marca de agua y el thumbnail, así que les dejos a ustedes, la posibilidad de cambiarlo a gusto, si lo pueden mejorar me gustaría que lo posteen.
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 20:16.