How to create image thumbnails of an existing image within the folder?

Asked

Viewed 2,127 times

3

inserir a descrição da imagem aqui

I’m learning to program, including learning VERY MUCH with the help of you who teach me practically everything about functions and my problem now is this: I need to create thumbnails of several width and height to suit each area of the site that has different image formats according to the page viewed.

How to develop a function com PHP which enters the folder of images and make copies of these images in the desired sizes type 620x400, 310x200, 155x100?

  • 3

    Your question is in the closing analysis queue and already has two votes to close as too wide. However, I see that you are already an experienced user here and your question seems to me well written, objective and well specified. So I think whoever voted to close this question should explain why, because I can’t see anything wrong with it. This way I’m voting "Leave it open".

  • 1

    I also marked to close as too wide because there are many variants. It’s actually easy to answer and the question is not so much the size of the answer, but the various variants. Example, how to organize images? Ever thought about it? Avoid name collision, avoid too many files in a single folder, etc.. And how much do you need to remove a specific image or a group of images? If the structure is not good, you will have a great difficulty in solving other problems that arise. So I consider it too broad. Try to ask one part at a time and you put the pieces together yourself.

  • @Danielomine he only asks how to create, you can not enlarge the question yourself if the AP just wants to know a detail, it was too wide if he asked "How can I create, remove, search PHP in Thumbs" for example.

  • I disagree, Jorbe B. For I insist that an adequate response would be too broad. He says in a passage "preciso criar thumbnails de diversos width e height". Imagine him creating this without planning the structure. And that’s the mistake every beginner makes. It would be simple if he asked only "quero redimensionar uma imagem". Then yes, in this case he turns with the structure. But, that’s not all he described. It is clear that he intends to apply this in several images. And as I said myself. The answer would not be long, but complex, with many variants.

1 answer

2

First keep in mind that image manipulation 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 exhausted (tried to allocate 13056 bytes) in thumbnail.php on line 36

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

You can rather try using 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 use 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 a little the server (if the script is used many times) and depending on the size of the image may occur the error already mentioned Allowed memory size.

What I recommend is to try using Javascript in front-end and upload using ajax, see a functional example here in another reply 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 the case must contain a publicly accessible path (via http).

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

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

By the desired path where the images will be saved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.