Foros del Web » Programando para Internet » PHP »

$_FILES y libreria GD

Estas en el tema de $_FILES y libreria GD en el foro de PHP en Foros del Web. Hola, llevo mucho tiempo leyendo el foro pero me he decidido a registrarme porque no he sido capaz de resolver un problema que me ronda ...
  #1 (permalink)  
Antiguo 04/04/2010, 13:56
Avatar de hardestbaby  
Fecha de Ingreso: abril-2010
Ubicación: Barcelona, Spain
Mensajes: 3
Antigüedad: 14 años
Puntos: 0
Exclamación $_FILES y libreria GD

Hola, llevo mucho tiempo leyendo el foro pero me he decidido a registrarme porque no he sido capaz de resolver un problema que me ronda desde hace dos días.

Estoy haciendo un gestor de noticias donde hay una pagina insertar.php que mediante un formulario POST con un input type file (name=foto) que lleva a insertar.proc.php donde a parte de otras cosas tengo lo siguiente:


Código PHP:
if($_FILES['foto']['name'] != ""){

        
$imagen$_FILES['foto']['name'];
        
$max_ancho 400;
        
$max_alto 400;
        list(
$ancho$alto) = getimagesize($imagen);

        
$x_ratio $max_ancho $ancho;
        
$y_ratio $max_alto $alto;

        if( (
$ancho <= $max_ancho) && ($alto <= $max_alto) ){
            
$nuevo_ancho $ancho;
            
$nuevo_alto $alto;
        }elseif ((
$x_ratio $alto) < $max_alto){
            
$nuevo_alto ceil($x_ratio $alto);
            
$nuevo_ancho $max_ancho;
        }else{
            
$nuevo_ancho ceil($y_ratio $ancho);
            
$nuevo_alto $max_alto;
        }
        
$source imagecreatefromjpeg($imagen);
        
$imagentemporal imagecreatetruecolor($nuevo_ancho,$nuevo_alto);
        
imagecopyresampled($imagentemporal,$source,0,0,0,0,$nuevo_ancho$nuevo_alto,$ancho,$alto);
        
$separar explode ("."$imagen);
        
$resized rand(0,9).rand(100,9999).rand(100,9999).".".$separar[1];
        
imagejpeg($imagentemporal"img/noticias/$resized");


Lo que hago con lo anterior, o quiero hacer, es que la imagen .jpg o .jpeg que viene del formulario la coja y la redimensione, la renombre con numeros aleatorios y además la guarde en una carpeta. Guardar solo la imagen redimensionada, no la original.

El caso es que falla el coger la imagen, falla $imagen= $_FILES['foto']['name']; . Todo lo demás funciona porque si pongo una imagen fija como $imagen="foto1.jpg"; si que funciona y lo hace todo bien.


Los errores son de que no guardan la imagen, pero si que reconocen el nombre del fichero:

Código PHP:
Warninggetimagesize(01.jpg) [function.getimagesize]: failed to open streamNo such file or directory in G:Program
asEasyPHPwwwgestor_noticiasinsertar_noticias.proc.php on line 17 
¿Qué estoy haciendo mal en este codigo?


Muchas gracias por la atención prestada,
un cordial saludo
  #2 (permalink)  
Antiguo 04/04/2010, 14:07
Avatar de locmasm  
Fecha de Ingreso: noviembre-2007
Ubicación: México D. F.
Mensajes: 301
Antigüedad: 16 años, 5 meses
Puntos: 1
Respuesta: $_FILES y libreria GD

Aquí está mi propuesta.

Yo iba a hacer lo mismo que tu, pero mejor busque un script que lo hiciera automáticamente... y la solución fue un script para hacer thumbs automáticamente, te lo digo por el uso que le he dado, te las redimensiona, por ejemplo:

Tu tienes una imagen de 800x750 y claro la quieres mas chica, al thumb le especificas por ejemplo x=400 y=400 esto significa que la redimensionara usando maximo 400 de ancho y 400 de alto, este es su limite, la redimensiona de tal modo que se vea bien usando como limite maximo 400 de ancho y alto.

Pruebalo, aquí te dejo el script e indicaciones, el script se llama Thumbnail Image Generator 1.3

En un images.class.php guarda esto:

Código PHP:
<?

class Zubrag_image {

  var 
$save_to_file true;
  var 
$image_type = -1;
  var 
$quality 100;
  var 
$max_x 100;
  var 
$max_y 100;
  var 
$cut_x 0;
  var 
$cut_y 0;
 
  function 
SaveImage($im$filename) {
 
    
$res null;
 
    
// ImageGIF is not included into some GD2 releases, so it might not work
    // output png if gifs are not supported
    
if(($this->image_type == 1)  && !function_exists('imagegif')) $this->image_type 3;

    switch (
$this->image_type) {
      case 
1:
        if (
$this->save_to_file) {
          
$res ImageGIF($im,$filename);
        }
        else {
          
header("Content-type: image/gif");
          
$res ImageGIF($im);
        }
        break;
      case 
2:
        if (
$this->save_to_file) {
          
$res ImageJPEG($im,$filename,$this->quality);
        }
        else {
          
header("Content-type: image/jpeg");
          
$res ImageJPEG($imNULL$this->quality);
        }
        break;
      case 
3:
        if (
PHP_VERSION >= '5.1.2') {
          
// Convert to PNG quality.
          // PNG quality: 0 (best quality, bigger file) to 9 (worst quality, smaller file)
          
$quality minround($this->quality 10), );
          if (
$this->save_to_file) {
            
$res ImagePNG($im$filename$quality);
          }
          else {
            
header("Content-type: image/png");
            
$res ImagePNG($imNULL$quality);
          }
        }
        else {
          if (
$this->save_to_file) {
            
$res ImagePNG($im$filename);
          }
          else {
            
header("Content-type: image/png");
            
$res ImagePNG($im);
          }
        }
        break;
    }
 
    return 
$res;
 
  }
 
  function 
ImageCreateFromType($type,$filename) {
   
$im null;
   switch (
$type) {
     case 
1:
       
$im ImageCreateFromGif($filename);
       break;
     case 
2:
       
$im ImageCreateFromJpeg($filename);
       break;
     case 
3:
       
$im ImageCreateFromPNG($filename);
       break;
    }
    return 
$im;
  }
 
  
// generate thumb from image and save it
  
function GenerateThumbFile($from_name$to_name) {
 
    
// if src is URL then download file first
    
$temp false;
    if (
substr($from_name,0,7) == 'http://') {
      
$tmpfname tempnam("tmp/""TmP-");
      
$temp = @fopen($tmpfname"w");
      if (
$temp) {
        @
fwrite($temp, @file_get_contents($from_name)) or die("Cannot download image");
        @
fclose($temp);
        
$from_name $tmpfname;
      }
      else {
        die(
"Cannot create temp file");
      }
    }

    
// check if file exists
    
if (!file_exists($from_name)) die("Source image does not exist!");
    
    
// get source image size (width/height/type)
    // orig_img_type 1 = GIF, 2 = JPG, 3 = PNG
    
list($orig_x$orig_y$orig_img_type$img_sizes) = @GetImageSize($from_name);

    
// cut image if specified by user
    
if ($this->cut_x 0$orig_x min($this->cut_x$orig_x);
    if (
$this->cut_y 0$orig_y min($this->cut_y$orig_y);
 
    
// should we override thumb image type?
    
$this->image_type = ($this->image_type != -$this->image_type $orig_img_type);
 
    
// check for allowed image types
    
if ($orig_img_type or $orig_img_type 3) die("Image type not supported");
 
    if (
$orig_x $this->max_x or $orig_y $this->max_y) {
 
      
// resize
      
$per_x $orig_x $this->max_x;
      
$per_y $orig_y $this->max_y;
      if (
$per_y $per_x) {
        
$this->max_x $orig_x $per_y;
      }
      else {
        
$this->max_y $orig_y $per_x;
      }
 
    }
    else {
      
// keep original sizes, i.e. just copy
      
if ($this->save_to_file) {
        @
copy($from_name$to_name);
      }
      else {
        switch (
$this->image_type) {
          case 
1:
              
header("Content-type: image/gif");
              
readfile($from_name);
            break;
          case 
2:
              
header("Content-type: image/jpeg");
              
readfile($from_name);
            break;
          case 
3:
              
header("Content-type: image/png");
              
readfile($from_name);
            break;
        }
      }
      return;
    }
 
    if (
$this->image_type == 1) {
      
// should use this function for gifs (gifs are palette images)
      
$ni imagecreate($this->max_x$this->max_y);
    }
    else {
      
// Create a new true color image
      
$ni ImageCreateTrueColor($this->max_x,$this->max_y);
    }
 
    
// Fill image with white background (255,255,255)
    
$white imagecolorallocate($ni255255255);
    
imagefilledrectangle$ni00$this->max_x$this->max_y$white);
    
// Create a new image from source file
    
$im $this->ImageCreateFromType($orig_img_type,$from_name);
    
// Copy the palette from one image to another
    
imagepalettecopy($ni,$im);
    
// Copy and resize part of an image with resampling
    
imagecopyresampled(
      
$ni$im,             // destination, source
      
0000,           // dstX, dstY, srcX, srcY
      
$this->max_x$this->max_y,       // dstW, dstH
      
$orig_x$orig_y);    // srcW, srcH
 
    // save thumb file
    
$this->SaveImage($ni$to_name);

    if(
$temp) {
      
unlink($tmpfname); // this removes the file
    
}

  }

}

?>
En thumb.php guarda esto

Código PHP:
<?
// Parameters:
// src - path to source image
// dest - path to thumb (where to save it)
// x - max width
// y - max height
// q - quality (applicable only to JPG, 1 to 100, 100 - best)
// t - thumb type. "-1" - same as source, 1 = GIF, 2 = JPG, 3 = PNG
// f - save to file (1) or output to browser (0).

// Sample usage: 
// 1. save thumb on server
// http://www.zubrag.com/thumb.php?src=test.jpg&dest=thumb.jpg&x=100&y=50
// 2. output thumb to browser
// http://www.zubrag.com/thumb.php?src=test.jpg&x=50&y=50&f=0


// Below are default values (if parameter is not passed)

// save to file (true) or output to browser (false)
$save_to_file true;

// Quality for JPEG and PNG.
// 0 (worst quality, smaller file) to 100 (best quality, bigger file)
// Note: PNG quality is only supported starting PHP 5.1.2
$image_quality 100;

// resulting image type (1 = GIF, 2 = JPG, 3 = PNG)
// enter code of the image type if you want override it
// or set it to -1 to determine automatically
$image_type = -1;

// maximum thumb side size
$max_x 100;
$max_y 100;

// cut image before resizing. Set to 0 to skip this.
$cut_x 0;
$cut_y 0;

// Folder where source images are stored (thumbnails will be generated from these images).
// MUST end with slash.
$images_folder '../imagenes/articulos/';

// Folder to save thumbnails, full path from the root folder, MUST end with slash.
// Only needed if you save generated thumbnails on the server.
// Sample for windows:     c:/wwwroot/thumbs/
// Sample for unix/linux:  /home/site.com/htdocs/thumbs/
$thumbs_folder '/www/thumbs/';


///////////////////////////////////////////////////
/////////////// DO NOT EDIT BELOW
///////////////////////////////////////////////////

$to_name '';

if (isset(
$_REQUEST['f'])) {
  
$save_to_file intval($_REQUEST['f']) == 1;
}

if (isset(
$_REQUEST['src'])) {
  
$from_name urldecode($_REQUEST['src']);
}
else {
  die(
"Source file name must be specified.");
}

if (isset(
$_REQUEST['dest'])) {
  
$to_name urldecode($_REQUEST['dest']);
}
else if (
$save_to_file) {
  die(
"Thumbnail file name must be specified.");
}

if (isset(
$_REQUEST['q'])) {
  
$image_quality intval($_REQUEST['q']);
}

if (isset(
$_REQUEST['t'])) {
  
$image_type intval($_REQUEST['t']);
}

if (isset(
$_REQUEST['x'])) {
  
$max_x intval($_REQUEST['x']);
}

if (isset(
$_REQUEST['y'])) {
  
$max_y intval($_REQUEST['y']);
}

if (!
file_exists($images_folder)) die('Images folder does not exist (update $images_folder in the script)');
if (
$save_to_file && !file_exists($thumbs_folder)) die('Thumbnails folder does not exist (update $thumbs_folder in the script)');

// Allocate all necessary memory for the image.
// Special thanks to Alecos for providing the code.
ini_set('memory_limit''-1');

// include image processing code
include('image.class.php');

$img = new Zubrag_image;

// initialize
$img->max_x        $max_x;
$img->max_y        $max_y;
$img->cut_x        $cut_x;
$img->cut_y        $cut_y;
$img->quality      $image_quality;
$img->save_to_file $save_to_file;
$img->image_type   $image_type;

// generate thumbnail
$img->GenerateThumbFile($images_folder $from_name$thumbs_folder $to_name);

?>
La forma de uso es así:

<img src="thumb.php?src=ejemplo.jpg&x=400&y=400&f=0" border="0" />

Puedes cambiar el valor de X y Y, si deseas más info, checa la pagina http://www.zubrag.com/scripts/thumbnail-generator.php

Saludos :D
  #3 (permalink)  
Antiguo 04/04/2010, 14:20
Avatar de hardestbaby  
Fecha de Ingreso: abril-2010
Ubicación: Barcelona, Spain
Mensajes: 3
Antigüedad: 14 años
Puntos: 0
Respuesta: $_FILES y libreria GD

Cita:
Iniciado por locmasm Ver Mensaje
Aquí está mi propuesta.

Yo iba a hacer lo mismo que tu, pero mejor busque un script que lo hiciera automáticamente... y la solución fue un script para hacer thumbs automáticamente, te lo digo por el uso que le he dado, te las redimensiona, por ejemplo:

Tu tienes una imagen de 800x750 y claro la quieres mas chica, al thumb le especificas por ejemplo x=400 y=400 esto significa que la redimensionara usando maximo 400 de ancho y 400 de alto, este es su limite, la redimensiona de tal modo que se vea bien usando como limite maximo 400 de ancho y alto.

Pruebalo, aquí te dejo el script e indicaciones, el script se llama Thumbnail Image Generator 1.3


Saludos :D
Muchas gracias por responder tan rápido!! Es genial el script que me has pasado, lo que ocurre que lo que estoy haciendo es para un proyecto de mis estudios y no es ético poner un script tan complejo cuando sabe el profesor que no entiendo tanto.

Igualmente le voy a pegar un ojo a ver si veo algo.

A ver si alguién más se anima y me ayuda, que se aprende mucho cuando te corrigen los errores.


gracias!!
  #4 (permalink)  
Antiguo 05/04/2010, 03:37
Avatar de hardestbaby  
Fecha de Ingreso: abril-2010
Ubicación: Barcelona, Spain
Mensajes: 3
Antigüedad: 14 años
Puntos: 0
Respuesta: $_FILES y libreria GD

Buenos días,

se me ha ocurrido que podría guardar la imagen cargada mendiante $_FILES mediante move_uploaded_files en un fichero temp.jpg, hacer todo el proceso con ese fichero y luego borrar el temp.jpg con unlink.

Voy a intentarlo, lo comento por si alguien quiere hacer lo mismo que yo y le sirve de ayuda. Cuando lo tenga acabado pegaré aqui el código.

De todas formas me gustaría que algun master del php me indicara porque no funciona el código original.


Gracias.
  #5 (permalink)  
Antiguo 29/05/2010, 06:18
DyDPersonal
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: $_FILES y libreria GD

El codigo original no funciona porque el "$_FILES['foto']['name']" no te da la URL de origen del archivo... solo te da el nombre... al darte el nombre no puedes omtener el tamaño del archivo y por lo tanto no puedes poner en funcionamiento la funcion...

lo mejor es acer lo que as dicho... guardar el archivo temporalmente y trabajar con el y una ves echo la redireccion borrar el archivo temporal...

Saludos!
  #6 (permalink)  
Antiguo 29/05/2010, 07:39
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: $_FILES y libreria GD

en todo caso el índice mas útil es tmp_name, ya que ese si te da la ruta completa del archivo temporal de la imagen... no hay necesidad de guardarlo de nuevo... ;)
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.

Etiquetas: files, libreria
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 23:53.