Generate image thumbnails on upload

Hey!

I am working on a website that uses a lot of images in various sizes and formats.

The fact that thumbnails are only generated when the url is called up does not work very well in my case. It’s not just the first load that is affected, but the subsequent ones (the images are lazy-loaded within a carousel, so you have to click to display the image to start the generation, and the server is sadly not fast).

I’ve been looking for a solution to generate the different sizes on upload, but without success so far. I saw that it was possible to do this with Janitor, but unfortunately I can’t install it yet because the server version of PHP doesn’t match (and it will take a while before I’m allowed to update the version).

In short, I’m trying an approach via a plugin, but the code below doesn’t seem to produce anything, no error, no thumb generated:

function testResize($file)
{
    if ($file->isResizable()) {
        try {
            $file->thumb([
                'width' => 300,
                'quality' => 80,
            ]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}

Kirby::plugin('studio-lambelet/image-generator', [
    'hooks' => [
        'file.create:after' => function ($file) {
            testResize($file);
        },
        'file.replace:after' => function ($newFile, $oldFile) {
            testResize($newFile);
        }
    ]
]);

Any help is welcome :heart_hands: Thank you!

To force create the thumb itself, and not just the job file, call

$file->thumb([
                'width' => 300,
                'quality' => 80,
            ])->save();
1 Like

Perfect, thank you so much!