Search code examples
phpthumbnailscropimage-resizing

Problem resizing image with crop php when I call it from external file don't show the image on online server


This is the file with the crop and Header example.

redimensionador.php

<?php
//Redimensionador

$nombre_archivo = "ajo_tradiciones.jpg";
$rutaCarpetas = "views/images/$nombre_archivo";

$img = imagecreatefromjpeg($rutaCarpetas);
$imgs = getimagesize($rutaCarpetas);


$w = $imgs[0];
$h = $imgs[1];


$escala_w = 70/$w;
$escala_h = 70/$h;

$nuevo_ancho = floor($w*$escala_w);
$nuevo_alto = floor($h*$escala_h);

$tp = imagecreatetruecolor($nuevo_ancho, $nuevo_alto);

imagecopyresampled($tp, $img, 0,0,0,0, 70, 70, $w, $h);

ob_clean();//Adding ob_clean I get it works on online server. 
//With this option I get view the image with the new size 70x70
Header("Content-type: image/jpeg");
imagejpeg($tp, NULL, 100);

imagedestroy($img);
?>

But if I call redimensionador from another file like crop-cargador.php it doesn't work.

crop-cargador.php

<p>Option resized from external file</p>
<img src="redimensionador.php" />
<p>Option resized from external file from folders route</p>
<img src="views/modules/redimensionador.php" />

All of them works in localhost but this last one example doesn't work on online server if I try to see the image from crop-cargador.php.

What should I do to solve the problem?


Solution

  • Finally I've used $_SERVER["DOCUMENT_ROOT"]; and apparently I got the solution.

    redimensionador.php

    <?php
        //Opción 1 para cargar desde otro archivo.
        //Nombre del archivo
        $nombre_archivo = "ajo_tradiciones.jpg";
        //Ruta absoluta desde el directorio Raiz del servidor.
        $rutaRaiz = $_SERVER["DOCUMENT_ROOT"];
        $rutaCarpetas = $rutaRaiz."/views/images/$nombre_archivo";//Carga
    
        $img = imagecreatefromjpeg($rutaCarpetas);
        $imgs = getimagesize($rutaCarpetas);
    
        $w = $imgs[0];
        $h = $imgs[1];
    
        $escala_w = 70/$w;
        $escala_h = 70/$h;
    
        $nuevo_ancho = floor($w*$escala_w);
        $nuevo_alto = floor($h*$escala_h);
    
        $tp = imagecreatetruecolor($nuevo_ancho, $nuevo_alto);
    
        imagecopyresampled($tp, $img, 0,0,0,0, 70, 70, $w, $h);
    
        ob_clean();
        //Con esta opción logro verla en pantalla con el nuevo tamaño 70x70
        Header("Content-type: image/jpeg");
        imagejpeg($tp, NULL, 100);
    
        imagedestroy($img);
        ?>
    

    crop-cargador.php

    <?php $url = Ruta::ctrRuta(); // https://dominio.com/ ?>
    <p>Cargo la imagen desde la ruta de la url absoluta.</p>
    <img src="<?php echo $url ?>views/modules/redimensionador.php" />
    

    So I share it just in case someone need it later.

    Greetings!