Cómo guardar una imagen externa en host de forma eficiente

  • Autor Autor Delmon
  • Fecha de inicio Fecha de inicio
Delmon

Delmon

Épsilon
Programador
Verificación en dos pasos activada
Verificado por Whatsapp
Hola colegas programadores, ando en el desarrollo de un nuevo sistema :$ y pues se me ocurrio la idea de poder guardar una imagen externa en mi host, para lo cual anduve indagando y encontré lo siguiente:

PHP:
function guardarImagenes($img, $nombre){
	$path = "imagenes/";//COLOCA EL DIRECTORIO DONDE SE GUARDARA
	$x = Descargar_imagen($img,$path."i".$nombre);
	$img_nueva_anchura = 150;	$img_nueva_altura = 200;	$img_nueva_calidad = 90;
	$ext = explode(".",$nombre);$i=0;
	while($ext[$i]!=""){$i++;}$i=$i-1;
    $defecto = 'imagenes/defecto.jpg';
    if(file_exists($path."i".$nombre)) {
        $ext[$i]=strtolower($ext[$i]);
        switch($ext[$i])
        {
            case 'jpeg':    $img = ImageCreateFromJPEG($path."i".$nombre);  break;
            case 'jpg':        $img = ImageCreateFromJPEG($path."i".$nombre);  break;
            case 'png':        $img = ImageCreateFromPNG($path."i".$nombre);breaK;
           default:        $img = ImageCreateFromJPEG($defecto); break;
        }
    } else
          $img = ImageCreateFromJPEG($defecto);

    $new_w_R = ImageSX($img);$new_h_R = ImageSY($img);
    $aspect_ratio = $new_h_R/$new_w_R;
    $img_nueva_altura = abs($img_nueva_anchura * $aspect_ratio);
    $thumb = ImageCreateTrueColor($img_nueva_anchura,$img_nueva_altura);
    ImageCopyResampled($thumb,$img,0,0,0,0,$img_nueva_anchura,$img_nueva_altura,ImageSX($img),ImageSY($img));
	imagejpeg($thumb, $path.$nombre, $img_nueva_calidad); //guarda la nueva imagen
	imagedestroy($thumb);
}

PHP:
function Descargar_imagen($url,$path) {
     $c = curl_init();
     curl_setopt($c,CURLOPT_URL,$url);
     curl_setopt($c,CURLOPT_HEADER,0);
     curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
     $s = curl_exec($c);
     curl_close($c);
     $f = fopen($path, 'wb');
     $z = fwrite($f,$s);
     if ($z != false) return 1;
     return 0;
 }

Luego de eso intenté ejecutar la función así


PHP:
guardarImagenes("http://www.geeksxd.com/wp-content/uploads/2011/05/windows-7-deshabilitar-aero-snap-300x213.jpg","prueba");
Y pues no me va... alguien me puede ayudar :$ o existe otra función :$?
 
Última edición:
y las demas funciones??? lo unico que quieres es guardar la imagen sin modifiar tamaño y eso????
antes que nada yo estaba usando snoopy para recorrer ciertas webs y la parte que supongo te interesa seria esta

PHP:
$img_file = file_get_contents($image);//$image es la url de la imagen ...

    $image_path = parse_url($image);
    $img_path_parts = pathinfo($image_path['path']);

    $filename = $img_path_parts['filename'];
    $img_ext = $img_path_parts['extension'];

    $path = "enciclopedia/"; // ya pues el path...
    $filex = $path . $filename . "." .$img_ext;
    $fh = fopen($filex, 'w');
    fputs($fh, $img_file);
 //aqui armaba despues la url porque la necesitaba para algo mas adelante
$imagenserie = "http://xxxxxxxx.com/images/series/enciclopedia/".$filename.".jpg";
 
Wao muchas gracias... llevaba varios días así y hasta hoy no encontraba una solución.

Si no fuera otra molestia me podrías decir si hay alguna funcion para cambiarle el tamaño :$?

Muchas Gracias!!!
 
Última edición:
Os complicais demasiado para bajar una simple imagen...

yo uso copy y listo, en mi servidor...


Un Saludo 😉
 
Os complicais demasiado para bajar una simple imagen...

yo uso copy y listo, en mi servidor...


Un Saludo 😉

Yo también intenté con la función copy, sin embargo al parecer mi host no soporta 🙁
 
Yo programé la siguiente función, no está comentada pero te explico como funciona:

PHP:
function thumb($file,$name){
    $patch = "micarpetadestino/$name.png"; // LA RUTA DEL ARCHIVO RESULTANTE
    if(file_exists($patch)){
        return $patch; // SI EXISTE UNA IAMGEN CON ESE NOMBRE, NO CREAMOS NADA Y DEVOLVEMOS LA RUTA
    }
    else{
        if(preg_match("/.gif/i", $file)){
            $source_image = imagecreatefromgif($file);
        }
        elseif(preg_match("/.png/i", $file)){
            $source_image = imagecreatefrompng($file);
        }
        else{
            $source_image = imagecreatefromjpeg($file);
        }
        $source_imagex = imagesx($source_image);
        $source_imagey = imagesy($source_image);
        
        if($source_imagex > $source_imagey){
            $biggestSide = $source_imagex;
        }
        else{
            $biggestSide = $source_imagey; 
        }
        
        $cropPercent = .7; // ESTE PORCENTAJE ES PARA CORTAR AL MEDIO Y QUE LA IAMGEN NO SE VEA DESPROPORCIONADA
        
        $cropWidth   = $biggestSide*$cropPercent; 
        $cropHeight  = $biggestSide*$cropPercent;
        
        $x = ($source_imagex-$cropWidth)/2;
        $y = ($source_imagey-$cropHeight)/2;
        
        $new_h = 60; // ALTO DE LA NUEVA IMAGEN
        $new_w = 100; // ANCHO DE LA NUEVA IMAGEN
        
        $dest_image = imagecreatetruecolor($new_w,$new_h);
        imagecopyresampled($dest_image,$source_image, 0, 0, $x, $y, $new_w, $new_w, $cropWidth, $cropHeight);
        if(imagejpeg($dest_image,$patch)){
            return $patch;
        }
        else{
            return 'micarpetadestino/default.jpg';
        }
    }
}

Avísame si te funciona, un saludo.
 
Atrás
Arriba