How to create thumbnails of images from an existing image inside the folder?

3

I am learning to program, even learning VERY with the help of you who teach me practically everything about functions and my problem now is this: thumbnails of various width and height to match each area of the site that has different image formats depending on the page viewed.

How to develop a function com PHP that goes into the images folder and makes copies of these images 620x400 , 310x200 , 155x100 ?

    
asked by anonymous 22.11.2015 / 17:23

1 answer

2

First keep in mind that manipulating images using PHP (or any other platform / language) usually consumes a lot of memory depending on the image, and may even cause an error similar to this:

  

Fatal error: Allowed memory size of 33554432 bytes thumbnail.php on line 36

This is practically almost impossible to solve, you can even soften it by setting it to php.ini memory_limit , but this is not the solution (in my opinion), since it still affects the server, even more in your in case it will probably be several images at the same time.

You can instead try to use a script like this (rename the file to resize.php):

<?php
function imageResize($path, $new_width, $new_height, $outputFolder)
{
    $mime = detectMimeType($path);

    switch ($mime) {
        case 'image/jpeg':
            $resource = imagecreatefromjpeg($path);
        break;
        case 'image/gif':
            $resource = imagecreatefrompng($path);
        break;
        case 'image/png':
            $resource = imagecreatefromgif($path);
        break;
        default:
            return false;
    }

    $filename = preg_replace('#\.[a-z]+$#i', '', basename($path));

    $width  = imagesx($resource);
    $height = imagesy($resource);

    if ($new_width >= $width && $new_height >= $height) {
        return false;
    }

    if ($width > $height) {
        $percentage = $width / $new_width;
    } else {
        $percentage = $height / $new_height;
    }

    $new_width  = round($width  * $percentage);
    $new_height = round($height * $percentage);

    $newImage = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($newImage, $resource, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    $resource = NULL;

    $filename .= '[' . $new_width . 'x' . $new_height . ']';

    switch ($mime) {
        case 'image/jpeg':
            imagejpeg($newImage, $outputFolder . '/' . $filename . '.jpg', 100);
        break;
        case 'image/gif':
            imagegif($newImage, $outputFolder . '/' . $filename . '.gif');
        break;
        default:
            imagepng($newImage, $outputFolder . '/' . $filename . '.png');
    }

    $newImage = NULL;
}

function detectMimeType($file)
{
    $mime = '';
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {
        $mime = mime_content_type($file);
    }

    return $mime;
}

The usage would look something like:

<?php
include 'resize.php';

$pastaDestino = 'redimensionadas/';
$arquivos = 'originais/';

//Pega todas imagens
$lista = glob($arquivos . '/*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);

foreach ($lista as $file) {
     //Se o arquivo se chamar foto.jpg gera um arquivo com o nome "foto[155x100].jpg"
     imageResize($file, 155, 100, $pastaDestino);

     //Gera um arquivo com o nome "foto[310x200].jpg"
     imageResize($file, 310, 200, $pastaDestino);

     //Gera um arquivo com o nome "foto[620x400].jpg"
     imageResize($file, 620, 400, $pastaDestino);
}

However as I said this can generate a high memory consumption which can affect the server a bit (if the script is used many times) and depending on the size of the image can occur the error already mentioned Allowed memory size .

What I recommend is to try to use Javascript on the front end and upload using ajax, see an example here functional in another answer of mine:

The only difference is that instead of using <input type=file> you should do so:

<?php
$arquivos = 'originais/';

//Pega todas imagens
$lista = glob($arquivos . '/*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
?>

<script>
<?php foreach ($lista as $file): ?>
<?php
    $filename = preg_replace('#\.[a-z]+$#i', '', basename($path));
?>
    var pathfile = "<?php echo $file; ?>";
    var filename = "<?php echo $filename; ?>";

    //155x100
    compressImage(pathfile, 155, 100, "jpeg", function(resource) {
        uploadAjax(resource, filename . '[155x100].jpg', function(response) {
            if (response === "OK") {
                alert("sucesso");
            } else {
                alert("Ajax: " + response);
            }
        }, function(errStatus) {
            alert("erro: " + errStatus);
        });
    });

    //310x200
    compressImage(pathfile, 310, 200, "jpeg", function(resource) {
        uploadAjax(resource, filename . '[310x200].jpg', function(response) {
            if (response === "OK") {
                alert("sucesso");
            } else {
                alert("Ajax: " + response);
            }
        }, function(errStatus) {
            alert("erro: " + errStatus);
        });
    });

    //620x400
    compressImage(pathfile, 620, 400, "jpeg", function(resource) {
        uploadAjax(resource, filename . '[620x400].jpg', function(response) {
            if (response === "OK") {
                alert("sucesso");
            } else {
                alert("Ajax: " + response);
            }
        }, function(errStatus) {
            alert("erro: " + errStatus);
        });
    });

<?php endforeach; ?>
</script>
  

Note that the pathfile or $ file in this case must contain a publicly accessible path (via http).

In the upload.php file (of the other question) change:

define('PASTA_UPLOAD', '/home/user/projeto/data');

By the desired path where the images will be saved.

    
23.11.2015 / 04:46