Foros del Web » Programando para Internet » PHP »

Guardar thumbnails

Estas en el tema de Guardar thumbnails en el foro de PHP en Foros del Web. Buenas amigos. Estoy teniendo algunos problemillas con la creación de thumbnails, concretamente a la hora de guardarlos en el servidor. No manejo muy bien las ...
  #1 (permalink)  
Antiguo 09/02/2010, 07:25
 
Fecha de Ingreso: marzo-2008
Mensajes: 207
Antigüedad: 16 años, 1 mes
Puntos: 0
Guardar thumbnails

Buenas amigos.

Estoy teniendo algunos problemillas con la creación de thumbnails, concretamente a la hora de guardarlos en el servidor.

No manejo muy bien las librerías GD, así que me he bajado algunos scripts para crear el thumbnail, pero todos lo muestran por pantalla, unos lo guardan en el server y otros no, pero siempre lo muestran. Yo no quiero mostrarlos, quiero crearlos y llamarlos luego cuando yo quiera. A parte de que no consigo que hagan los thumbnails sin copiar la imagen externa a mi propio server (quiero poder pillar una imagen a partir de su url, crear un thumbnail a partir de esa imagen y guardar esa imagen en el server).

Lo que quiero poder hacer eso algo parecido a esto:

Código PHP:
Ver original
  1. <?php
  2.   function crear_thumbnail($url, $width, $height, $destino)
  3.  {
  4.     $thumbnail = redimensionar($url ,$width, $height);
  5.     $grabar($thumbnail, $destino);
  6.  }
  7.  
  8.  crear_thumbnail("http://www.dominio.com/imagen.jpg", 100, 100, "thumbnail.jpg");
  9.  
  10.  echo "<img src='thumbnail.jpg' />";
  11. ?>

Ya no sé cómo hacerlo. Casi lo he conseguido editando el script timthumb.php de Wordpress, pero me sale la imagen de tan mala calidad que ni se distinguen las formas. Lo que no quiero es tener que llamar en el src de la imagen al script, porque necesito que esa llamada sea estática, debido a que la página que administro genera un home estática al día para reducir la carga del servidor, para que no se sobrecargue por las visitas (sí, se carga muchísimo, y la home tiene muchos scripts, así que la tengo que cachear una vez al día).

¿Alguna idea de cómo guardar el thumbnail sin mostrarlo? El resto de funciones para generar el tumbnail las puedo apañar yo con el chorro de scripts que me bajado y lo que ya tengo aprendido de tanto leer y modificar, pero me gustaría que me ayudárais con la parte de guardar sin mostrar, que es que me trae por la calle de la amargura TT_____TT ...

Muchas gracias por adelantado.


Un saludo.
  #2 (permalink)  
Antiguo 09/02/2010, 08:15
Avatar de jackson666  
Fecha de Ingreso: noviembre-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 1.971
Antigüedad: 14 años, 5 meses
Puntos: 65
Respuesta: Guardar thumbnails

Te dejo una clase que tenia yo hace tiempo que te la guarda despues de redimensionarla

Código PHP:
class ImgHandler{

    var 
$imagen;//nombre de la imagen cargada
    
var $ext;//extension nueva imagen cargada
    
    
var $ancho;//ancho de nueva imagen
    
var $alto;//alto de nueva imagen
    
    
function __construct($ruta){
        if(
file_exists($ruta)){
        
$this->imagen=$ruta;
    }else{
        echo 
"Ruta de Imagen Incorrecta";
    }
        return 
true;
    }
    
    function 
resizeImg($newName,$width,$height){
        
        
$tamano=getimagesize($this->imagen);
        
$this->ancho=$tamano[0];
        
$this->alto=$tamano[1];
                    
        
$imagenRedim=imagecreatetruecolor($width,$height);      
       
        list(
$nombre,$extension)=explode(".",$this->imagen);
        
$this->ext=$extension;
        
        if(empty(
$newName)){
            
$newName=$nombre;
        }        
        
        echo 
"<br /><b>Nombre de la Imagen Original:</b> ".$this->imagen."<br /><br />";
        echo 
"<b>Nombre de la Imagen Transformada:</b> ".$newName.".".$this->ext."<br /><br />";
        
        echo 
"<u>Tamaño de la Imagen Original:</u><br />Ancho--> ".$tamano[0]."<br />Alto---> ".$tamano[1]."<br /><br />";
        echo 
"<u>Tamaño de la Imagen Transformada:</u><br />Ancho--> ".$width."<br />Alto---> ".$height."<br /><br />";
       
        if(
strtolower($this->ext)=="jpg" or strtolower($this->ext)=="jpeg"){
            
$crear=imagecreatefromjpeg($this->imagen);
            
imagecopyresampled($imagenRedim,$crear,0,0,0,0,$width,$height,$this->ancho,$this->alto);
            
imagejpeg($imagenRedim,$newName.".jpg",100);
            echo 
"Formato---> jpg<br />";
            
imagedestroy($crear);
       
        }else if(
strtolower($this->ext)=="png"){
            echo 
"Formato---> png<br />";
            
$crear=imagecreatefrompng($this->imagen);
            
imagecopyresampled($imagenRedim,$crear,0,0,0,0,$width,$height,$this->ancho,$this->alto);
            
imagepng($imagenRedim,$newName.".png");
            
imagedestroy($crear);
                
        }else if(
strtolower($this->ext)=="gif"){
            echo 
"Formato---> gif<br />";
            
$crear=imagecreatefromgif($this->imagen);
            
imagecopyresampled($imagenRedim,$crear,0,0,0,0,$width,$height,$this->ancho,$this->alto);
            
imagegif($imagenRedim,$newName.".gif");
            
imagedestroy($crear);
        
        }else{
            echo 
"<b><font color='red'>El nombre o extension de la imagen es Incorrecto</font></b>";
        }
       
    }
   
    function 
scaleImg($newName,$percent){
        
       
#echo "<br /><b>Nombre de Imagen:</b> ".$this->imagen."<br />";
        
        
$tamano=getimagesize($this->imagen);
        
$this->ancho=$tamano[0];
        
$this->alto=$tamano[1];
        
        
#Redimension
        
$finalWidth=$this->ancho*$percent;
        
$finalHeight=$this->alto*$percent;
        
        
$imgEscalada=imagecreatetruecolor($finalWidth,$finalHeight);
               
        list(
$noSirve,$sirve)=explode(".",$this->imagen);
        
$this->ext=$sirve;        
       
        if(
strtolower($this->ext)=="jpg" or strtolower($this->ext)=="jpeg"){
            
#echo "Formato---> jpg<br />";
            
$crear=imagecreatefromjpeg($this->imagen);
            
imagecopyresampled($imgEscalada,$crear,0,0,0,0,$finalWidth,$finalHeight,$this->ancho,$this->alto);
            
imagejpeg($imgEscalada,$newName.".jpg",100);
                  
        }else if(
strtolower($this->ext)=="png"){
            
#echo "Formato---> png<br />";
            
$crear=imagecreatefrompng($this->imagen);
            
imagecopyresampled($imgEscalada,$crear,0,0,0,0,$finalWidth,$finalHeight,$this->ancho,$this->alto);
            
imagepng($imgEscalada,$newName.".png");
       
        }else if(
strtolower($this->ext)=="gif"){
            
#echo "Formato---> gif<br />";
            
$crear=imagecreatefromgif($this->imagen);
            
imagecopyresampled($imgEscalada,$crear,0,0,0,0,$finalWidth,$finalHeight,$this->ancho,$this->alto);
            
imagegif($imgEscalada,$newName.".gif");
        }
        
    }

Para usarlo:

Ejemplo de escala

Código PHP:
<?php
include("imghandler.class.php");

$thumb=new ImgHandler("img/1.jpg");

$thumb->scaleImg("1",0.35);
?>
Ejemplo de redimension

Código PHP:
<?php
include("imghandler.class.php");

$thumb=new ImgHandler("img/1.jpg");

$thumb->resizeImg("algo"100100);
?>
Modificalo a gusto para que te lo guarde donde quieras...
__________________
HV Studio
Diseño y desarrollo web
  #3 (permalink)  
Antiguo 09/02/2010, 08:37
 
Fecha de Ingreso: marzo-2008
Mensajes: 207
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: Guardar thumbnails

Gracias, es más fácil de leer que los scripts con los que estaba trabajando, a ver si le puedo sacar partido a éste.

Muchas gracias por tu ayuda. Lo pruebo y vuelvo con los resultados.
  #4 (permalink)  
Antiguo 09/02/2010, 14:23
(Desactivado)
 
Fecha de Ingreso: abril-2008
Mensajes: 787
Antigüedad: 16 años
Puntos: 7
Respuesta: Guardar thumbnails

perdon por entrometerme, una consulta jackson666. tu has desarrollado un aporte sobre redimension de imagenes con escala ?.

saludos.
  #5 (permalink)  
Antiguo 09/02/2010, 21:54
Avatar de jackson666  
Fecha de Ingreso: noviembre-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 1.971
Antigüedad: 14 años, 5 meses
Puntos: 65
Respuesta: Guardar thumbnails

Nop, esta clase es una que yo tenia por ahi dando vueltas... No la he puesto como aporte
__________________
HV Studio
Diseño y desarrollo web
  #6 (permalink)  
Antiguo 10/02/2010, 08:02
(Desactivado)
 
Fecha de Ingreso: abril-2008
Mensajes: 787
Antigüedad: 16 años
Puntos: 7
Respuesta: Guardar thumbnails

entiendo.

saludos.
  #7 (permalink)  
Antiguo 11/02/2010, 09:09
 
Fecha de Ingreso: marzo-2008
Mensajes: 207
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: Guardar thumbnails

Pues chico, no me ha servido, no me reconoce el directorio :S ...

Pongo el código del timthumb.php de Wordpress, que hace unos thumbnails estupendos, a ver si alguien me puede decir qué insertar y dónde para poder copiar el thumbnail generado en cache y pegarlo con otro nombre para poder llamarlo luego desde la home estática.

Código PHP:
Ver original
  1. <?php
  2. /*
  3.     TimThumb script created by Tim McDaniels and Darren Hoyt with tweaks by Ben Gillbanks
  4.     http://code.google.com/p/timthumb/
  5.  
  6.     MIT License: http://www.opensource.org/licenses/mit-license.php
  7.  
  8.     Paramters
  9.     ---------
  10.     w: width
  11.     h: height
  12.     zc: zoom crop (0 or 1)
  13.     q: quality (default is 75 and max is 100)
  14.    
  15.     HTML example: <img src="/scripts/timthumb.php?src=/images/whatever.jpg&w=150&h=200&zc=1" alt="" />
  16. */
  17.  
  18. /*
  19. $sizeLimits = array(
  20.     "100x100",
  21.     "150x150",
  22. );
  23.  
  24. error_reporting(E_ALL);
  25. ini_set("display_errors", 1);
  26. */
  27.  
  28. // check to see if GD function exist
  29. if(!function_exists('imagecreatetruecolor')) {
  30.     displayError('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
  31. }
  32.  
  33. define ('CACHE_SIZE', 250);        // number of files to store before clearing cache
  34. define ('CACHE_CLEAR', 5);        // maximum number of files to delete on each cache clear
  35. define ('VERSION', '1.11');        // version number (to force a cache refresh
  36.  
  37. if (function_exists('imagefilter') && defined('IMG_FILTER_NEGATE')) {
  38.     $imageFilters = array(
  39.         "1" => array(IMG_FILTER_NEGATE, 0),
  40.         "2" => array(IMG_FILTER_GRAYSCALE, 0),
  41.         "3" => array(IMG_FILTER_BRIGHTNESS, 1),
  42.         "4" => array(IMG_FILTER_CONTRAST, 1),
  43.         "5" => array(IMG_FILTER_COLORIZE, 4),
  44.         "6" => array(IMG_FILTER_EDGEDETECT, 0),
  45.         "7" => array(IMG_FILTER_EMBOSS, 0),
  46.         "8" => array(IMG_FILTER_GAUSSIAN_BLUR, 0),
  47.         "9" => array(IMG_FILTER_SELECTIVE_BLUR, 0),
  48.         "10" => array(IMG_FILTER_MEAN_REMOVAL, 0),
  49.         "11" => array(IMG_FILTER_SMOOTH, 0),
  50.     );
  51. }
  52.  
  53. // sort out image source
  54. $src = get_request("src", "");
  55. if($src == '' || strlen($src) <= 3) {
  56.     displayError ('no image specified');
  57. }
  58.  
  59. // clean params before use
  60. $src = cleanSource($src);
  61. // last modified time (for caching)
  62. $lastModified = filemtime($src);
  63.  
  64. // get properties
  65. $new_width         = preg_replace("/[^0-9]+/", "", get_request("w", 0));
  66. $new_height     = preg_replace("/[^0-9]+/", "", get_request("h", 0));
  67. $zoom_crop         = preg_replace("/[^0-9]+/", "", get_request("zc", 1));
  68. $quality         = preg_replace("/[^0-9]+/", "", get_request("q", 80));
  69. $filters        = get_request("f", "");
  70.  
  71. if ($new_width == 0 && $new_height == 0) {
  72.     $new_width = 100;
  73.     $new_height = 100;
  74. }
  75.  
  76. // set path to cache directory (default is ./tmp)
  77. // this can be changed to a different location
  78. $cache_dir = '../img/thumbnails_portada/tmp';
  79.  
  80. // get mime type of src
  81. $mime_type = mime_type($src);
  82.  
  83. // check to see if this image is in the cache already
  84. check_cache ($cache_dir, $mime_type);
  85.  
  86. // if not in cache then clear some space and generate a new file
  87. cleanCache();
  88.  
  89. ini_set('memory_limit', "50M");
  90.  
  91. // make sure that the src is gif/jpg/png
  92. if(!valid_src_mime_type($mime_type)) {
  93.     displayError("Invalid src mime type: " .$mime_type);
  94. }
  95.  
  96. if(strlen($src) && file_exists($src)) {
  97.  
  98.     // open the existing image
  99.     $image = open_image($mime_type, $src);
  100.     if($image === false) {
  101.         displayError('Unable to open image : ' . $src);
  102.     }
  103.  
  104.     // Get original width and height
  105.     $width = imagesx($image);
  106.     $height = imagesy($image);
  107.    
  108.     // generate new w/h if not provided
  109.     if( $new_width && !$new_height ) {
  110.        
  111.         $new_height = $height * ( $new_width / $width );
  112.        
  113.     } elseif($new_height && !$new_width) {
  114.        
  115.         $new_width = $width * ( $new_height / $height );
  116.        
  117.     } elseif(!$new_width && !$new_height) {
  118.        
  119.         $new_width = $width;
  120.         $new_height = $height;
  121.        
  122.     }
  123.    
  124.     // create a new true color image
  125.     $canvas = imagecreatetruecolor( $new_width, $new_height );
  126.     imagealphablending($canvas, false);
  127.     // Create a new transparent color for image
  128.     $color = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
  129.     // Completely fill the background of the new image with allocated color.
  130.     imagefill($canvas, 0, 0, $color);
  131.     // Restore transparency blending
  132.     imagesavealpha($canvas, true);
  133.  
  134.     if( $zoom_crop ) {
  135.  
  136.         $src_x = $src_y = 0;
  137.         $src_w = $width;
  138.         $src_h = $height;
  139.  
  140.         $cmp_x = $width  / $new_width;
  141.         $cmp_y = $height / $new_height;
  142.  
  143.         // calculate x or y coordinate and width or height of source
  144.  
  145.         if ( $cmp_x > $cmp_y ) {
  146.  
  147.             $src_w = round( ( $width / $cmp_x * $cmp_y ) );
  148.             $src_x = round( ( $width - ( $width / $cmp_x * $cmp_y ) ) / 2 );
  149.  
  150.         } elseif ( $cmp_y > $cmp_x ) {
  151.  
  152.             $src_h = round( ( $height / $cmp_y * $cmp_x ) );
  153.             $src_y = round( ( $height - ( $height / $cmp_y * $cmp_x ) ) / 2 );
  154.  
  155.         }
  156.        
  157.         imagecopyresampled( $canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h );
  158.  
  159.     } else {
  160.  
  161.         // copy and resize part of an image with resampling
  162.         imagecopyresampled( $canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
  163.  
  164.     }
  165.    
  166.     if ($filters != '' && function_exists('imagefilter') && defined('IMG_FILTER_NEGATE')) {
  167.         // apply filters to image
  168.         $filterList = explode("|", $filters);
  169.         foreach($filterList as $fl) {
  170.             $filterSettings = explode(",", $fl);
  171.             if(isset($imageFilters[$filterSettings[0]])) {
  172.            
  173.                 for($i = 0; $i < 4; $i ++) {
  174.                     if(!isset($filterSettings[$i])) {
  175.                         $filterSettings[$i] = null;
  176.                     }
  177.                 }
  178.                
  179.                 switch($imageFilters[$filterSettings[0]][1]) {
  180.                
  181.                     case 1:
  182.                    
  183.                         imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
  184.                         break;
  185.                    
  186.                     case 2:
  187.                    
  188.                         imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
  189.                         break;
  190.                    
  191.                     case 3:
  192.                    
  193.                         imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
  194.                         break;
  195.                    
  196.                     default:
  197.                    
  198.                         imagefilter($canvas, $imageFilters[$filterSettings[0]][0]);
  199.                         break;
  200.                        
  201.                 }
  202.             }
  203.         }
  204.     }
  205.    
  206.     // output image to browser based on mime type
  207.     show_image($mime_type, $canvas, $cache_dir);
  208.    
  209.     // remove image from memory
  210.     imagedestroy($canvas);
  211.    
  212. } else {
  213.  
  214.     if(strlen($src)) {
  215.         displayError("image " . $src . " not found");
  216.     } else {
  217.         displayError("no source specified");
  218.     }
  219.    
  220. }
  221.  
  222. /**
  223.  *
  224.  */
  225. function show_image($mime_type, $image_resized, $cache_dir) {
  226.  
  227.     global $quality;
  228.  
  229.     // check to see if we can write to the cache directory
  230.     $is_writable = 0;
  231.     $cache_file_name = $cache_dir . '/' . get_cache_file();
  232.  
  233.     if (touch($cache_file_name)) {
  234.        
  235.         // give 666 permissions so that the developer
  236.         // can overwrite web server user
  237.         chmod ($cache_file_name, 0666);
  238.         $is_writable = 1;
  239.        
  240.     } else {
  241.        
  242.         $cache_file_name = NULL;
  243.         header ('Content-type: ' . $mime_type);
  244.        
  245.     }
  246.  
  247.     switch ($mime_type) {
  248.    
  249.         case 'image/jpeg':
  250.             imagejpeg($image_resized, $cache_file_name, $quality);
  251.             break;
  252.        
  253.         default :
  254.             $quality = floor ($quality * 0.09);
  255.             imagepng($image_resized, $cache_file_name, $quality);
  256.            
  257.     }
  258.    
  259.     if ($is_writable) {
  260.         show_cache_file ($cache_dir, $mime_type);
  261.     }
  262.  
  263.     imagedestroy ($image_resized);
  264.    
  265.     displayError ("error showing image");
  266.  
  267. }
  268.  
  269. /**
  270.  *
  271.  */
  272. function get_request( $property, $default = 0 ) {
  273.    
  274.     if( isset($_REQUEST[$property]) ) {
  275.    
  276.         return $_REQUEST[$property];
  277.        
  278.     } else {
  279.    
  280.         return $default;
  281.        
  282.     }
  283.    
  284. }
  285.  
  286. /**
  287.  *
  288.  */
  289. function open_image($mime_type, $src) {
  290.  
  291.     $mime_type = strtolower($mime_type);
  292.    
  293.     if (stristr ($mime_type, 'gif')) {
  294.    
  295.         $image = imagecreatefromgif($src);
  296.        
  297.     } elseif (stristr($mime_type, 'jpeg')) {
  298.    
  299.         @ini_set ('gd.jpeg_ignore_warning', 1);
  300.         $image = imagecreatefromjpeg($src);
  301.        
  302.     } elseif (stristr ($mime_type, 'png')) {
  303.    
  304.         $image = imagecreatefrompng($src);
  305.        
  306.     }
  307.    
  308.     return $image;
  309.  
  310. }
  311. ?>
  #8 (permalink)  
Antiguo 11/02/2010, 09:11
 
Fecha de Ingreso: marzo-2008
Mensajes: 207
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: Guardar thumbnails

Pego el resto del código, que no me cabía en un sólo post:

Código PHP:
Ver original
  1. <?php
  2. /**
  3.  * clean out old files from the cache
  4.  * you can change the number of files to store and to delete per loop in the defines at the top of the code
  5.  */
  6. function cleanCache() {
  7.  
  8.     $files = glob("cache/*", GLOB_BRACE);
  9.    
  10.     if (count($files) > 0) {
  11.    
  12.         $yesterday = time() - (24 * 60 * 60);
  13.        
  14.         usort($files, 'filemtime_compare');
  15.         $i = 0;
  16.        
  17.         if (count($files) > CACHE_SIZE) {
  18.            
  19.             foreach ($files as $file) {
  20.                
  21.                 $i ++;
  22.                
  23.                 if ($i >= CACHE_CLEAR) {
  24.                     return;
  25.                 }
  26.                
  27.                 if (@filemtime($file) > $yesterday) {
  28.                     return;
  29.                 }
  30.                
  31.                 if (file_exists($file)) {
  32.                     unlink($file);
  33.                 }
  34.                
  35.             }
  36.            
  37.         }
  38.        
  39.     }
  40.  
  41. }
  42.  
  43.  
  44. /**
  45.  * compare the file time of two files
  46.  */
  47. function filemtime_compare($a, $b) {
  48.  
  49.     return filemtime($a) - filemtime($b);
  50.    
  51. }
  52.  
  53.  
  54. /**
  55.  * determine the file mime type
  56.  */
  57. function mime_type($file) {
  58.  
  59.     if (stristr(PHP_OS, 'WIN')) {
  60.         $os = 'WIN';
  61.     } else {
  62.         $os = PHP_OS;
  63.     }
  64.  
  65.     $mime_type = '';
  66.  
  67.     if (function_exists('mime_content_type')) {
  68.         $mime_type = mime_content_type($file);
  69.     }
  70.    
  71.     // use PECL fileinfo to determine mime type
  72.     if (!valid_src_mime_type($mime_type)) {
  73.         if (function_exists('finfo_open')) {
  74.             $finfo = @finfo_open(FILEINFO_MIME);
  75.             if ($finfo != '') {
  76.                 $mime_type = finfo_file($finfo, $file);
  77.                 finfo_close($finfo);
  78.             }
  79.         }
  80.     }
  81.  
  82.     // try to determine mime type by using unix file command
  83.     // this should not be executed on windows
  84.     if (!valid_src_mime_type($mime_type) && $os != "WIN") {
  85.         if (preg_match("/FREEBSD|LINUX/", $os)) {
  86.             $mime_type = trim(@shell_exec('file -bi ' . escapeshellarg($file)));
  87.         }
  88.     }
  89.  
  90.     // use file's extension to determine mime type
  91.     if (!valid_src_mime_type($mime_type)) {
  92.  
  93.         // set defaults
  94.         $mime_type = 'image/png';
  95.         // file details
  96.         $fileDetails = pathinfo($file);
  97.         $ext = strtolower($fileDetails["extension"]);
  98.         // mime types
  99.         $types = array(
  100.              'jpg'  => 'image/jpeg',
  101.              'jpeg' => 'image/jpeg',
  102.              'png'  => 'image/png',
  103.              'gif'  => 'image/gif'
  104.          );
  105.        
  106.         if (strlen($ext) && strlen($types[$ext])) {
  107.             $mime_type = $types[$ext];
  108.         }
  109.        
  110.     }
  111.    
  112.     return $mime_type;
  113.  
  114. }
  115.  
  116.  
  117. /**
  118.  *
  119.  */
  120. function valid_src_mime_type($mime_type) {
  121.  
  122.     if (preg_match("/jpg|jpeg|gif|png/i", $mime_type)) {
  123.         return true;
  124.     }
  125.    
  126.     return false;
  127.  
  128. }
  129.  
  130.  
  131. /**
  132.  *
  133.  */
  134. function check_cache ($cache_dir, $mime_type) {
  135.  
  136.     // make sure cache dir exists
  137.     if (!file_exists($cache_dir)) {
  138.         // give 777 permissions so that developer can overwrite
  139.         // files created by web server user
  140.         mkdir($cache_dir);
  141.         chmod($cache_dir, 0777);
  142.     }
  143.  
  144.     show_cache_file ($cache_dir, $mime_type);
  145.  
  146. }
  147.  
  148.  
  149. /**
  150.  *
  151.  */
  152. function show_cache_file ($cache_dir, $mime_type) {
  153.  
  154.     $cache_file = $cache_dir . '/' . get_cache_file();
  155.  
  156.     if (file_exists($cache_file)) {
  157.        
  158.         $gmdate_mod = gmdate("D, d M Y H:i:s", filemtime($cache_file));
  159.        
  160.         if(! strstr($gmdate_mod, "GMT")) {
  161.             $gmdate_mod .= " GMT";
  162.         }
  163.        
  164.         if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
  165.        
  166.             // check for updates
  167.             $if_modified_since = preg_replace ("/;.*$/", "", $_SERVER["HTTP_IF_MODIFIED_SINCE"]);
  168.            
  169.             if ($if_modified_since == $gmdate_mod) {
  170.                 header("HTTP/1.1 304 Not Modified");
  171.                 die();
  172.             }
  173.  
  174.         }
  175.        
  176.         $fileSize = filesize ($cache_file);
  177.        
  178.         // send headers then display image
  179.         header ('Content-Type: ' . $mime_type);
  180.         header ('Accept-Ranges: bytes');
  181.         header ('Last-Modified: ' . $gmdate_mod);
  182.         header ('Content-Length: ' . $fileSize);
  183.         header ('Cache-Control: max-age=9999, must-revalidate');
  184.         header ('Expires: ' . $gmdate_mod);
  185.        
  186.         readfile ($cache_file);
  187.        
  188.         die();
  189.  
  190.     }
  191.    
  192. }
  193.  
  194.  
  195. /**
  196.  *
  197.  */
  198. function get_cache_file() {
  199.  
  200.     global $lastModified;
  201.     static $cache_file;
  202.    
  203.     if (!$cache_file) {
  204.         $cachename = $_SERVER['QUERY_STRING'] . VERSION . $lastModified;
  205.         $cache_file = md5($cachename) . '.png';
  206.     }
  207.    
  208.     return $cache_file;
  209.  
  210. }
  211.  
  212.  
  213. /**
  214.  * check to if the url is valid or not
  215.  */
  216. function valid_extension ($ext) {
  217.  
  218.     if (preg_match("/jpg|jpeg|png|gif/i", $ext)) {
  219.         return TRUE;
  220.     } else {
  221.         return FALSE;
  222.     }
  223.    
  224. }
  225.  
  226.  
  227. /**
  228.  *
  229.  */
  230. function checkExternal ($src) {
  231.  
  232.     $allowedSites = array(
  233.         'flickr.com',
  234.         'picasa.com',
  235.         'blogger.com',
  236.         'wordpress.com',
  237.     );
  238.  
  239.     if (ereg('http://', $src) == true) {
  240.    
  241.         $url_info = parse_url ($src);
  242.        
  243.         $isAllowedSite = false;
  244.         foreach ($allowedSites as $site) {
  245.             if (ereg($site, $url_info['host']) == true) {
  246.                 $isAllowedSite = true;
  247.             }
  248.         }
  249.        
  250.         if ($isAllowedSite) {
  251.        
  252.             $filename = explode('/', $src);
  253.             $local_filepath = 'temp/' . $filename[count($filename) - 1];
  254.            
  255.             if (!file_exists($local_filepath)) {
  256.                
  257.                 if (function_exists('curl_init')) {
  258.                
  259.                     $fh = fopen($local_filepath, 'w');
  260.                     $ch = curl_init($src);
  261.                    
  262.                     curl_setopt($ch, CURLOPT_URL, $src);
  263.                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  264.                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  265.                     curl_setopt($ch, CURLOPT_HEADER, 0);
  266.                     curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
  267.                     curl_setopt($ch, CURLOPT_FILE, $fh);
  268.                    
  269.                     if (curl_exec($ch) === FALSE) {
  270.                         if (file_exists($local_filepath)) {
  271.                             unlink($local_filepath);
  272.                         }
  273.                         displayError('error reading file ' . $src . ' from remote host: ' . curl_error($ch));
  274.                     }
  275.                    
  276.                     curl_close($ch);
  277.                     fclose($fh);
  278.  
  279.                 } else {
  280.            
  281.                     if (!$img = file_get_contents($src)) {
  282.                         displayError('remote file for ' . $src . ' can not be accessed. It is likely that the file permissions are restricted');
  283.                     }
  284.                    
  285.                     if (file_put_contents($local_filepath, $img) == FALSE) {
  286.                         displayError('error writing temporary file');
  287.                     }
  288.                    
  289.                 }
  290.                
  291.                 if (!file_exists($local_filepath)) {
  292.                     displayError('local file for ' . $src . ' can not be created');
  293.                 }
  294.                
  295.             }
  296.            
  297.             $src = $local_filepath;
  298.            
  299.         } else {
  300.        
  301.             displayError('remote host "' . $url_info['host'] . '" not allowed');
  302.            
  303.         }
  304.        
  305.     }
  306.    
  307.     return $src;
  308.    
  309. }
  310.  
  311.  
  312.  
  313. /**
  314.  * tidy up the image source url
  315.  */
  316. function cleanSource($src) {
  317.  
  318.     $src = str_replace('http://' . $_SERVER['HTTP_HOST'], '', $src);
  319.     $src = str_replace('https://' . $_SERVER['HTTP_HOST'], '', $src);
  320.     $src = htmlentities($src);
  321.  
  322.     $src = checkExternal ($src);
  323.    
  324.     // remove slash from start of string
  325.     if(strpos($src, '/') === 0) {
  326.         $src = substr($src, -(strlen($src) - 1));
  327.     }
  328.  
  329.     // remove http/ https/ ftp
  330.     $src = preg_replace("/^((ht|f)tp(s|):\/\/)/i", '', $src);
  331.     // remove domain name from the source url
  332.     $host = $_SERVER['HTTP_HOST'];
  333.     $src = str_replace($host, '', $src);
  334.     $host = str_replace('www.', '', $host);
  335.     $src = str_replace($host, '', $src);
  336.  
  337.     // don't allow users the ability to use '../'
  338.     // in order to gain access to files below document root
  339.  
  340.     // src should be specified relative to document root like:
  341.     // src=images/img.jpg or src=/images/img.jpg
  342.     // not like:
  343.     // src=../images/img.jpg
  344.     $src = preg_replace("/\.\.+\//", "", $src);
  345.    
  346.     // get path to image on file system
  347.     $src = get_document_root($src) . '/' . $src;
  348.  
  349.     return $src;
  350.  
  351. }
  352. ?>
  #9 (permalink)  
Antiguo 11/02/2010, 09:11
 
Fecha de Ingreso: marzo-2008
Mensajes: 207
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: Guardar thumbnails

Y el resto del código:

Código PHP:
Ver original
  1. <?php
  2.  
  3. /**
  4.  *
  5.  */
  6. function get_document_root ($src) {
  7.  
  8.     // check for unix servers
  9.     if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $src)) {
  10.         return $_SERVER['DOCUMENT_ROOT'];
  11.     }
  12.  
  13.     // check from script filename (to get all directories to timthumb location)
  14.     $parts = array_diff(explode('/', $_SERVER['SCRIPT_FILENAME']), explode('/', $_SERVER['DOCUMENT_ROOT']));
  15.     $path = $_SERVER['DOCUMENT_ROOT'];
  16.     foreach ($parts as $part) {
  17.         $path .= '/' . $part;
  18.         if (file_exists($path . '/' . $src)) {
  19.             return $path;
  20.         }
  21.     }    
  22.    
  23.     // the relative paths below are useful if timthumb is moved outside of document root
  24.     // specifically if installed in wordpress themes like mimbo pro:
  25.     // /wp-content/themes/mimbopro/scripts/timthumb.php
  26.     $paths = array(
  27.         ".",
  28.         "..",
  29.         "../..",
  30.         "../../..",
  31.         "../../../..",
  32.         "../../../../.."
  33.     );
  34.    
  35.     foreach ($paths as $path) {
  36.         if(file_exists($path . '/' . $src)) {
  37.             return $path;
  38.         }
  39.     }
  40.    
  41.     // special check for microsoft servers
  42.     if (!isset($_SERVER['DOCUMENT_ROOT'])) {
  43.         $path = str_replace("/", "\\", $_SERVER['ORIG_PATH_INFO']);
  44.         $path = str_replace($path, "", $_SERVER['SCRIPT_FILENAME']);
  45.        
  46.         if (file_exists($path . '/' . $src)) {
  47.             return $path;
  48.         }
  49.     }    
  50.    
  51.     displayError('file not found ' . $src);
  52.  
  53. }
  54.  
  55.  
  56. /**
  57.  * generic error message
  58.  */
  59. function displayError($errorString = '') {
  60.  
  61.     header('HTTP/1.1 400 Bad Request');
  62.     die($errorString);
  63.    
  64. }
  65. ?>

Lo ideal sería del tirón crear el thumbnail a partir de la imagen externa (sin tener que copiarla a mi servidor, como estoy haciendo ahora mismo, y guardar el thumbnail en una carpeta con un nombre dado y poder llamarlo luego desde la home estática, pero con tantas funciones me hago un lío.

¿Alguien que sepa ayudarme?

Muchas gracias a todos y perdón por pegaros tanto código :( .
  #10 (permalink)  
Antiguo 11/02/2010, 21:40
Avatar de jackson666  
Fecha de Ingreso: noviembre-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 1.971
Antigüedad: 14 años, 5 meses
Puntos: 65
Respuesta: Guardar thumbnails

Como que no te reconoce el directorio? La probe ahora mismo y funciona bien! Agarro una imagen que esta en un directorio, la transformo y la guardo en otro distinto!
__________________
HV Studio
Diseño y desarrollo web
  #11 (permalink)  
Antiguo 13/07/2010, 09:34
 
Fecha de Ingreso: marzo-2009
Mensajes: 13
Antigüedad: 15 años, 1 mes
Puntos: 0
Respuesta: Guardar thumbnails

Cita:
Iniciado por jackson666 Ver Mensaje
Te dejo una clase que tenia yo hace tiempo que te la guarda despues de redimensionarla

Código PHP:
class ImgHandler{

    var 
$imagen;//nombre de la imagen cargada
    
var $ext;//extension nueva imagen cargada
    
    
var $ancho;//ancho de nueva imagen
    
var $alto;//alto de nueva imagen
    
    
function __construct($ruta){
        if(
file_exists($ruta)){
        
$this->imagen=$ruta;
    }else{
        echo 
"Ruta de Imagen Incorrecta";
    }
        return 
true;
    }
    
    function 
resizeImg($newName,$width,$height){
        
        
$tamano=getimagesize($this->imagen);
        
$this->ancho=$tamano[0];
        
$this->alto=$tamano[1];
                    
        
$imagenRedim=imagecreatetruecolor($width,$height);      
       
        list(
$nombre,$extension)=explode(".",$this->imagen);
        
$this->ext=$extension;
        
        if(empty(
$newName)){
            
$newName=$nombre;
        }        
        
        echo 
"<br /><b>Nombre de la Imagen Original:</b> ".$this->imagen."<br /><br />";
        echo 
"<b>Nombre de la Imagen Transformada:</b> ".$newName.".".$this->ext."<br /><br />";
        
        echo 
"<u>Tamaño de la Imagen Original:</u><br />Ancho--> ".$tamano[0]."<br />Alto---> ".$tamano[1]."<br /><br />";
        echo 
"<u>Tamaño de la Imagen Transformada:</u><br />Ancho--> ".$width."<br />Alto---> ".$height."<br /><br />";
       
        if(
strtolower($this->ext)=="jpg" or strtolower($this->ext)=="jpeg"){
            
$crear=imagecreatefromjpeg($this->imagen);
            
imagecopyresampled($imagenRedim,$crear,0,0,0,0,$width,$height,$this->ancho,$this->alto);
            
imagejpeg($imagenRedim,$newName.".jpg",100);
            echo 
"Formato---> jpg<br />";
            
imagedestroy($crear);
       
        }else if(
strtolower($this->ext)=="png"){
            echo 
"Formato---> png<br />";
            
$crear=imagecreatefrompng($this->imagen);
            
imagecopyresampled($imagenRedim,$crear,0,0,0,0,$width,$height,$this->ancho,$this->alto);
            
imagepng($imagenRedim,$newName.".png");
            
imagedestroy($crear);
                
        }else if(
strtolower($this->ext)=="gif"){
            echo 
"Formato---> gif<br />";
            
$crear=imagecreatefromgif($this->imagen);
            
imagecopyresampled($imagenRedim,$crear,0,0,0,0,$width,$height,$this->ancho,$this->alto);
            
imagegif($imagenRedim,$newName.".gif");
            
imagedestroy($crear);
        
        }else{
            echo 
"<b><font color='red'>El nombre o extension de la imagen es Incorrecto</font></b>";
        }
       
    }
   
    function 
scaleImg($newName,$percent){
        
       
#echo "<br /><b>Nombre de Imagen:</b> ".$this->imagen."<br />";
        
        
$tamano=getimagesize($this->imagen);
        
$this->ancho=$tamano[0];
        
$this->alto=$tamano[1];
        
        
#Redimension
        
$finalWidth=$this->ancho*$percent;
        
$finalHeight=$this->alto*$percent;
        
        
$imgEscalada=imagecreatetruecolor($finalWidth,$finalHeight);
               
        list(
$noSirve,$sirve)=explode(".",$this->imagen);
        
$this->ext=$sirve;        
       
        if(
strtolower($this->ext)=="jpg" or strtolower($this->ext)=="jpeg"){
            
#echo "Formato---> jpg<br />";
            
$crear=imagecreatefromjpeg($this->imagen);
            
imagecopyresampled($imgEscalada,$crear,0,0,0,0,$finalWidth,$finalHeight,$this->ancho,$this->alto);
            
imagejpeg($imgEscalada,$newName.".jpg",100);
                  
        }else if(
strtolower($this->ext)=="png"){
            
#echo "Formato---> png<br />";
            
$crear=imagecreatefrompng($this->imagen);
            
imagecopyresampled($imgEscalada,$crear,0,0,0,0,$finalWidth,$finalHeight,$this->ancho,$this->alto);
            
imagepng($imgEscalada,$newName.".png");
       
        }else if(
strtolower($this->ext)=="gif"){
            
#echo "Formato---> gif<br />";
            
$crear=imagecreatefromgif($this->imagen);
            
imagecopyresampled($imgEscalada,$crear,0,0,0,0,$finalWidth,$finalHeight,$this->ancho,$this->alto);
            
imagegif($imgEscalada,$newName.".gif");
        }
        
    }

Para usarlo:

Ejemplo de escala

Código PHP:
<?php
include("imghandler.class.php");

$thumb=new ImgHandler("img/1.jpg");

$thumb->scaleImg("1",0.35);
?>
Ejemplo de redimension

Código PHP:
<?php
include("imghandler.class.php");

$thumb=new ImgHandler("img/1.jpg");

$thumb->resizeImg("algo"100100);
?>
Modificalo a gusto para que te lo guarde donde quieras...
No me funciona con imagenes externas, Alguien sabe los cambios que hay que haber para que funcione con imagenes externas al servidor.

el erro que me da es este, pero solo con imagnes externas:
Código:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /home/..../public_html/..../imghandler.class.php  on line 21
gracias por su tiempo.

Etiquetas: thumbnails
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:29.