New addon - ImageOptimizer

Very simple addon that integrates with Spatie Image Optimizer and provides out of the box image optimization when saving an asset - https://github.com/pauloamgomes/CockpitCMS-ImageOptimizer

Interesting that checking some cloud services (e.g. tinypng, resmush, kraken, etc…) and differences in file size are minimal when compared with the available php binaries that are used by Spatie library.

2 Likes

Thank you for the contribution @pauloamgomes !

But you should consider using the filestorage service so the addon will also work with cloudstorage providers.

e.g. (not tested)

$app->on('cockpit.asset.save', function(&$asset) {  
    
    $stream = $this->filestorage->readStream("assets://{$asset['path'}");

    if (!$stream) {
        return;
    }

    $this->filestorage->writeStream("uploads://{$asset['path']}", $stream);
    $file = $this->path("#uploads:{$asset['path']}");

    $mime = $asset['mime'] ?? mime_content_type($file);
    \Spatie\ImageOptimizer\OptimizerChainFactory::create()->optimize($file);
    $asset['size'] = filesize($file);

    $this->filestorage->writeStream("assets://{$asset['path'}", fopen($file, 'r+'), ['mimetype' => $asset['mime']]);

});
1 Like

Yeah, but that causes some other issues, the second writeStream needs to be updateStream instead and thinking better using the cockpit.asset.save will have some overhead (saving twice same image), using now the cockpit.asset.upload instead.

good idea, but I would check whether the asset is an image or not.

The Optimiser class does that already.