Foros del Web » Creando para Internet » Diseño web »

redimensionar imagenes con php

Estas en el tema de redimensionar imagenes con php en el foro de Diseño web en Foros del Web. Hola a todos. Estoy haciendo una pagina en donde la jente puede dejar comentarios y subir fotos. La foto la pongo al lado del comentario. ...
  #1 (permalink)  
Antiguo 25/01/2009, 08:36
Avatar de miros84  
Fecha de Ingreso: diciembre-2008
Mensajes: 351
Antigüedad: 15 años, 4 meses
Puntos: 4
redimensionar imagenes con php

Hola a todos. Estoy haciendo una pagina en donde la jente puede dejar comentarios y subir fotos. La foto la pongo al lado del comentario. Pero es que si uno sube una foto 2000px por 2000 px, luego queda muy feo. Ocupa mas de la pantalla del monitor. Por eso la quiero redimensionar. Si añado simplemente width="233" height="233" en la variable de la imagen, es muy simple hacer lo, pero no todas las imagenes son cuadradas. Entonces se me ha ocurrido utilizar $size = GetImageSize("foto1.jpg"); para saber el ancho y el alto de la imagen. Y luego creo un if-esle para redimensionarla, pero creo que no lo redacto bien. alguien me podria decir donde me equiboco y por que ne errores? Este es el codigo:

$size = GetImageSize("foto1.jpg");
if($size[0] < 300 and $size[1] < 300)
{$shrch="$size[0]" and $visoch="$size[1];}
elseif ($size[0] > 300 and $size[0] < 700 and $size[1] > 300 and $size[1] < 700)
{$shrch="$size[0] /2" and $visoch="$size[1] /2";} //divido a 2
elseif ($size[0] > 700 and $size[0] < 1500 and $size[1] > 700 and $size[1] < 1500)
{$shrch="$size[0] /4" and $visoch="$size[1] /4";} //divido a 4

Si alguien sabe algun codigo mas inteligente, que me lo exponga por favor

Última edición por miros84; 25/01/2009 a las 08:43
  #2 (permalink)  
Antiguo 25/01/2009, 15:40
Avatar de ElJavista
Colaborador
 
Fecha de Ingreso: marzo-2007
Ubicación: Lima Perú
Mensajes: 2.231
Antigüedad: 17 años, 1 mes
Puntos: 67
Respuesta: redimensionar imagenes con php

Mira, si solo quieres modificar el tamaño por HTML eso no es nada eficiente porque si es una imagen muy grande igual se va a demorar mucho en cargar. Aquí tienes una clase para cambiar el tamaño de una imagen. Puedes cambiar una de sus dimensiones, ancho o alto y automáticamente la otra dimensión queda proporcionada, también puedes definir unas dimensiones máxmas, también aparecerá la imágen de manera proporcional, otra opcion es cortarla en dimensiones específicas.

Código PHP:
<?php
    
class Imagen {
          var 
$entrada "";
          var 
$width 0;
          var 
$height 0;
          var 
$tipo 0;

          function 
Imagen($ent) {
                   
$this->entrada $ent;
                   list(
$wid$hei$tip) = getimagesize($ent);
                   
$this->width $wid;
                   
$this->height $hei;
                   
$this->tipo $tip;
          }

          function 
getThumb($w$h$salida$opc false) {
                   
$ent $this->entrada;
                   
$tip $this->tipo;
                   
$wid $this->width;
                   
$hei $this->height;

                   if (
$w) {
                      
$newwidth $w;
                      
$newheight round(($hei $wid) * $newwidth);
                   }  elseif (
$h) {
                      
$newheight $h;
                      
$newwidth round(($wid $hei) * $newheight);
                   }
                   
// Cargar la imagen
                   
$thumb imagecreatetruecolor($newwidth$newheight);
                   if (
$tip == 1) {
                      
$source imagecreatefromgif($ent);
                   }  elseif (
$tip == 2) {
                      
$source imagecreatefromjpeg($ent);
                   }  elseif (
$tip == 3) {
                      
$source imagecreatefrompng($ent);
                   }

                   
// Redimensionar
                   
imagecopyresampled($thumb$source0000$newwidth$newheight$wid$hei);

                   
// Mostrar la nueva imagen
                   
if ($opc) return $thumb;
                   else return 
imagejpeg($thumb$salida);
          }

          function 
getNothumb($w$h$salida$opc false) {
                   
$ent $this->entrada;
                   
$tip $this->tipo;
                   
$wid $this->width;
                   
$hei $this->height;

                   if (
$h) {
                      
$newheight $h;
                      
$newwidth round(($wid $hei) * $newheight);
                   }  else if (
$w) {
                      
$newwidth $w;
                      
$newheight round(($hei $wid) * $newwidth);
                   }
                   
// Cargar la imagen
                   
$thumb imagecreatetruecolor($newwidth$newheight);
                   if (
$tip == 1) {
                      
$source imagecreatefromgif($ent);
                   }  elseif (
$tip == 2) {
                      
$source imagecreatefromjpeg($ent);
                   }  elseif (
$tip == 3) {
                      
$source imagecreatefrompng($ent);
                   }

                   
// Redimensionar
                   
imagecopyresampled($thumb$source0000$newwidth$newheight$wid$hei);

                   
// Mostrar la nueva imagen
                   
if ($opc) return $thumb;
                   else return 
imagejpeg($thumb$salida);
          }

          function 
getCorte($we$he$salida$opc false) {
                   
$img $this->entrada;
                   
$wid $this->width;
                   
$hei $this->height;
                   
$tip $this->tipo;

                   if (
$wid $we $hei $he) {
                      
$hp $hei;
                      
$wp round(($we $he) * $hp);
                   }  else {
                      
$wp $wid;
                      
$hp round(($he $we) * $wp);
                   }

                   
$lp round(($wid $wp) / 2);
                   
$tp round(($hei $hp) / 2);

                   
$thumb imagecreatetruecolor($we$he);
                   if (
$tip == 1) {
                     
$source imagecreatefromgif($img);
                    }  elseif (
$tip == 2) {
                     
$source imagecreatefromjpeg($img);
                   }  elseif (
$tip == 3) {
                     
$source imagecreatefrompng($img);
                   }

                   
imagecopyresampled($thumb$source00$lp$tp$we$he$wp$hp);

                   if (
$opc) return $thumb;
                   else return 
imagejpeg($thumb$salida);
          }
    }

    if (isset(
$_GET["img"])) {
       
$img = new Imagen($_GET["img"]);
       
$tip $_GET["tip"];
       
$w $_GET["w"];
       
$h $_GET["h"];

       
header("Content-type: image/jpeg");
       if (
$tip == 0) {
          
imagejpeg($img->getThumb($w$h""true));
       }  elseif (
$tip == 1) {
          
imagejpeg($img->getNothumb($w$h""true));
       }  elseif (
$tip == 2) {
          
imagejpeg($img->getCorte($w$h""true));
       }
    }
?>
Este es un ejemplo de su uso: digamos yo tengo una imagen llamada "imagen.jpg", entonces hago lo siguiente:

Código PHP:
include("class.imagen.php");
$img = new Imgen("imagen.jpg");
if (
$img->getThumb(100100"nuevaimgen.jpg")) echo "se generó la nueva imagen"
Si usas el método getNothumb entonces defines el ancho y alto máximo que puede tener la imagen y si usas el método getCorte entonces creas un corte de la imagen. Eso es interesante, porque digamos tienes una imagen de 600 x 800 y creas un corte de 100 x 100 no vas a crear un cuadro de 100 x 100 de la imagen original sino en realidad una reducción del corte de 600 x 600 de la imagen original, o sea, trata de abarcar la mayor área posible.

Bien, este archivo también se puede usar de la siguiente manera:

<img src="class.imagen.php?img=imagen.jpg&tip=2&w=100&h =100" />

Esto insertará una imagen de corte de 100 x 100 de la imagen origina. Bueno ya tienes varias opciones, tú decide. Espero que te sirva.
[/PHP]
  #3 (permalink)  
Antiguo 26/01/2009, 07:51
Avatar de miros84  
Fecha de Ingreso: diciembre-2008
Mensajes: 351
Antigüedad: 15 años, 4 meses
Puntos: 4
Respuesta: redimensionar imagenes con php

Muchas gracias por tu ayuda. Ahora voy a probar todo esto.
  #4 (permalink)  
Antiguo 13/10/2009, 10:45
Avatar de JessicaTJ  
Fecha de Ingreso: enero-2007
Ubicación: 127.0.0.1
Mensajes: 472
Antigüedad: 17 años, 3 meses
Puntos: 25
Respuesta: redimensionar imagenes con php

Otro tema viejito revivido xD

Bueno chicos, aki una pekeña pregunta, primero el codigo:
Código PHP:
<?php
    
class Imagen {
          var 
$entrada "";
          var 
$width 0;
          var 
$height 0;
          var 
$tipo 0;

          function 
Imagen($ent) {
                   
$this->entrada $ent;
                   list(
$wid$hei$tip) = getimagesize($ent);
                   
$this->width $wid;
                   
$this->height $hei;
                   
$this->tipo $tip;
          }

          function 
getThumb($w$h$salida$opc false) {
                   
$ent $this->entrada;
                   
$tip $this->tipo;
                   
$wid $this->width;
                   
$hei $this->height;

                   if (
$w) {
                      
$newwidth $w;
                      
$newheight round(($hei $wid) * $newwidth);
                   }  elseif (
$h) {
                      
$newheight $h;
                      
$newwidth round(($wid $hei) * $newheight);
                   }
                   
// Cargar la imagen
                   
$thumb imagecreatetruecolor($newwidth$newheight);
                   if (
$tip == 1) {
                      
$source imagecreatefromgif($ent);
                   }  elseif (
$tip == 2) {
                      
$source imagecreatefromjpeg($ent);
                   }  elseif (
$tip == 3) {
                      
$source imagecreatefrompng($ent);
                   }

                   
// Redimensionar
                   
imagecopyresampled($thumb$source0000$newwidth$newheight$wid$hei);

                   
// Mostrar la nueva imagen
                   
if ($opc) return $thumb;
                   else return 
imagejpeg($thumb$salida);
          }

          function 
getNothumb($w$h$salida$opc false) {
                   
$ent $this->entrada;
                   
$tip $this->tipo;
                   
$wid $this->width;
                   
$hei $this->height;

                   if (
$h) {
                      
$newheight $h;
                      
$newwidth round(($wid $hei) * $newheight);
                   }  else if (
$w) {
                      
$newwidth $w;
                      
$newheight round(($hei $wid) * $newwidth);
                   }
                   
// Cargar la imagen
                   
$thumb imagecreatetruecolor($newwidth$newheight);
                   if (
$tip == 1) {
                      
$source imagecreatefromgif($ent);
                   }  elseif (
$tip == 2) {
                      
$source imagecreatefromjpeg($ent);
                   }  elseif (
$tip == 3) {
                      
$source imagecreatefrompng($ent);
                   }

                   
// Redimensionar
                   
imagecopyresampled($thumb$source0000$newwidth$newheight$wid$hei);

                   
// Mostrar la nueva imagen
                   
if ($opc) return $thumb;
                   else return 
imagejpeg($thumb$salida);
          }

          function 
getCorte($we$he$salida$opc false) {
                   
$img $this->entrada;
                   
$wid $this->width;
                   
$hei $this->height;
                   
$tip $this->tipo;

                   if (
$wid $we $hei $he) {
                      
$hp $hei;
                      
$wp round(($we $he) * $hp);
                   }  else {
                      
$wp $wid;
                      
$hp round(($he $we) * $wp);
                   }

                   
$lp round(($wid $wp) / 2);
                   
$tp round(($hei $hp) / 2);

                   
$thumb imagecreatetruecolor($we$he);
                   if (
$tip == 1) {
                     
$source imagecreatefromgif($img);
                    }  elseif (
$tip == 2) {
                     
$source imagecreatefromjpeg($img);
                   }  elseif (
$tip == 3) {
                     
$source imagecreatefrompng($img);
                   }

                   
imagecopyresampled($thumb$source00$lp$tp$we$he$wp$hp);

                   if (
$opc) return $thumb;
                   else return 
imagejpeg($thumb$salida);
          }
    }

    if (isset(
$_GET["img"])) {
       
$img = new Imagen($_GET["img"]);
       
$tip $_GET["tip"];
       
$w $_GET["w"];
       
$h $_GET["h"];

       
header("Content-type: image/jpeg");
       if (
$tip == 0) {
          
imagejpeg($img->getThumb($w$h""true));
       }  elseif (
$tip == 1) {
          
imagejpeg($img->getNothumb($w$h""true));
       }  elseif (
$tip == 2) {
          
imagejpeg($img->getCorte($w$h""true));
       }
    }
?>
Funciona perfectamente, pero, cuando hay un folder por ejemplo, que tiene un simbolo de + me regresa esto:

Código:
Warning: getimagesize(images/prod1 /ShownDividerDPB.jpg) [function.getimagesize]: failed to open stream: No such file or directory in /home/user/public_html/class.image.php on line 10

Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/class.image.php:10) in /home/user/public_html/class.image.php on line 117

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/user/public_html/class.image.php on line 104
�����JFIF���������>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality ���C�    $.' ",#(7),01444'9=82<.342���C  2!!22222222222222222222222222222222222222222222222222����d�d"�������������� �������}�!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz����������������������������������������������������������������������������������� ������w�!1AQaq"2�B���� #3R�br� $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�����������������������������������������������������������������������������?����(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��
La direccion en la URL kedaria algo asi:
dominio.com/class.image.php?img=images/prod1+/ShownDividerDPB.jpg&tip=2&h=100&w=100

Alguna idea del porke hace esto?
__________________
٩(͡๏̯͡๏)۶ || ٩(͡๏̯͡๏)۶
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 07:39.