1. Go to this page and download the library: Download spatie/image-optimizer library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
spatie / image-optimizer example snippets
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($pathToImage);
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($pathToImage, $pathToOutput);
use Spatie\ImageOptimizer\Image;
use Spatie\ImageOptimizer\Optimizer;
$optimizerChain
->throws(function (Throwable $exception, Optimizer $optimizer, Image $image) {
report($exception);
// return to continue the chain, or throw to abort it
})
->optimize($pathToImage);
use Spatie\ImageOptimizer\OptimizerChain;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;
use Spatie\ImageOptimizer\Optimizers\Pngquant;
$optimizerChain = (new OptimizerChain)
->addOptimizer(new Jpegoptim([
'--strip-all',
'--all-progressive',
]))
->addOptimizer(new Pngquant([
'--force',
]))
namespace Spatie\ImageOptimizer\Optimizers;
use Spatie\ImageOptimizer\Image;
interface Optimizer
{
/**
* Returns the name of the binary to be executed.
*
* @return string
*/
public function binaryName(): string;
/**
* Determines if the given image can be handled by the optimizer.
*
* @param \Spatie\ImageOptimizer\Image $image
*
* @return bool
*/
public function canHandle(Image $image): bool;
/**
* Set the path to the image that should be optimized.
*
* @param string $imagePath
*
* @return $this
*/
public function setImagePath(string $imagePath);
/**
* Set the options the optimizer should use.
*
* @param array $options
*
* @return $this
*/
public function setOptions(array $options = []);
/**
* Get the command that should be executed.
*
* @return string
*/
public function getCommand(): string;
}
use Psr\Log\LoggerInterface;
use Spatie\ImageOptimizer\Image;
use Spatie\ImageOptimizer\Optimizers\BaseSelfHandlingOptimizer;
class ApiOptimizer extends BaseSelfHandlingOptimizer
{
public function canHandle(Image $image): bool
{
return $image->mime() === 'image/jpeg';
}
public function handle(Image $image, LoggerInterface $logger): void
{
// Optimize $image->path() however you like, e.g. by calling an API,
// and write the optimized bytes back to that path. Throw on failure.
// The chain's logger is passed in so you can log your progress.
}
}
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain
->useLogger(new MyLogger())
->optimize($pathToImage);