Giter Club home page Giter Club logo

image-optimizer's Introduction

Easily optimize images using PHP

Latest Version on Packagist Tests Total Downloads

This package can optimize PNGs, JPGs, WEBPs, AVIFs, SVGs and GIFs by running them through a chain of various image optimization tools. Here's how you can use it:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain->optimize($pathToImage);

The image at $pathToImage will be overwritten by an optimized version which should be smaller. The package will automatically detect which optimization binaries are installed on your system and use them.

Here are some example conversions that have been done by this package.

Loving Laravel? Then head over to the Laravel specific integration.

Using WordPress? Then try out the WP CLI command.

SilverStripe enthusiast? Don't waste time, go to the SilverStripe module.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/image-optimizer

Optimization tools

The package will use these optimizers if they are present on your system:

Here's how to install all the optimizers on Ubuntu/Debian:

sudo apt-get install jpegoptim
sudo apt-get install optipng
sudo apt-get install pngquant
sudo npm install -g svgo
sudo apt-get install gifsicle
sudo apt-get install webp
sudo apt-get install libavif-bin # minimum 0.9.3

And here's how to install the binaries on MacOS (using Homebrew):

brew install jpegoptim
brew install optipng
brew install pngquant
npm install -g svgo
brew install gifsicle
brew install webp
brew install libavif

And here's how to install the binaries on Fedora/RHEL/CentOS:

sudo dnf install epel-release
sudo dnf install jpegoptim
sudo dnf install optipng
sudo dnf install pngquant
sudo npm install -g svgo
sudo dnf install gifsicle
sudo dnf install libwebp-tools
sudo dnf install libavif-tools

Which tools will do what?

The package will automatically decide which tools to use on a particular image.

JPGs

JPGs will be made smaller by running them through JpegOptim. These options are used:

  • -m85: this will store the image with 85% quality. This setting seems to satisfy Google's Pagespeed compression rules
  • --strip-all: this strips out all text information such as comments and EXIF data
  • --all-progressive: this will make sure the resulting image is a progressive one, meaning it can be downloaded using multiple passes of progressively higher details.

PNGs

PNGs will be made smaller by running them through two tools. The first one is Pngquant 2, a lossy PNG compressor. We set no extra options, their defaults are used. After that we run the image through a second one: Optipng. These options are used:

  • -i0: this will result in a non-interlaced, progressive scanned image
  • -o2: this set the optimization level to two (multiple IDAT compression trials)

SVGs

SVGs will be minified by SVGO. SVGO's default configuration will be used, with the omission of the cleanupIDs and removeViewBox plugins because these are known to cause troubles when displaying multiple optimized SVGs on one page.

Please be aware that SVGO can break your svg. You'll find more info on that in this excellent blogpost by Sara Soueidan.

GIFs

GIFs will be optimized by Gifsicle. These options will be used:

  • -O3: this sets the optimization level to Gifsicle's maximum, which produces the slowest but best results

WEBPs

WEBPs will be optimized by Cwebp. These options will be used:

  • -m 6 for the slowest compression method in order to get the best compression.
  • -pass 10 for maximizing the amount of analysis pass.
  • -mt multithreading for some speed improvements.
  • -q 90 Quality factor that brings the least noticeable changes.

(Settings are original taken from here)

AVIFs

AVIFs will be optimized by avifenc. These options will be used:

  • -a cq-level=23: Constant Quality level. Lower values mean better quality and greater file size (0-63).
  • -j all: Number of jobs (worker threads, all uses all available cores).
  • --min 0: Min quantizer for color (0-63).
  • --max 63: Max quantizer for color (0-63).
  • --minalpha 0: Min quantizer for alpha (0-63).
  • --maxalpha 63: Max quantizer for alpha (0-63).
  • -a end-usage=q Rate control mode set to Constant Quality mode.
  • -a tune=ssim: SSIM as tune the encoder for distortion metric.

(Settings are original taken from here and here)

Usage

This is the default way to use the package:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain->optimize($pathToImage);

The image at $pathToImage will be overwritten by an optimized version which should be smaller.

The package will automatically detect which optimization binaries are installed on your system and use them.

To keep the original image, you can pass through a second argumentoptimize:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain->optimize($pathToImage, $pathToOutput);

In that example the package won't touch $pathToImage and write an optimized version to $pathToOutput.

Setting a timeout

You can set the maximum of time in seconds that each individual optimizer in a chain can use by calling setTimeout:

$optimizerChain
    ->setTimeout(10)
    ->optimize($pathToImage);

In this example each optimizer in the chain will get a maximum 10 seconds to do it's job.

Creating your own optimization chains

If you want to customize the chain of optimizers you can do so by adding Optimizers manually to an OptimizerChain.

Here's an example where we only want optipng and jpegoptim to be used:

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',
   ]))

Notice that you can pass the options an Optimizer should use to its constructor.

Writing a custom optimizers

Want to use another command line utility to optimize your images? No problem. Just write your own optimizer. An optimizer is any class that implements the Spatie\ImageOptimizer\Optimizers\Optimizer interface:

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;
}

If you want to view an example implementation take a look at the existing optimizers shipped with this package.

You can easily add your optimizer by using the addOptimizer method on an OptimizerChain.

use Spatie\ImageOptimizer\ImageOptimizerFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain
   ->addOptimizer(new YourCustomOptimizer())
   ->optimize($pathToImage);

Logging the optimization process

By default the package will not throw any errors and just operate silently. To verify what the package is doing you can set a logger:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain
   ->useLogger(new MyLogger())
   ->optimize($pathToImage);

A logger is a class that implements Psr\Log\LoggerInterface. A good logging library that's fully compliant is Monolog. The package will write to log which Optimizers are used, which commands are executed and their output.

Example conversions

Here are some real life example conversions done by this package.

Methodology for JPG, WEBP, AVIF images: the original image has been fed to spatie/image (using the default GD driver) and resized to 2048px width:

Spatie\Image\Image::load('original.jpg')
    ->width(2048)
    ->save('image.jpg'); // image.png, image.webp, image.avif

jpg

Original Original
771 KB

Optimized Optimized
511 KB (-33.7%, DSSIM: 0.00052061)

credits: Jeff Sheldon, via Unsplash

webp

Original Original
461 KB

Optimized Optimized
184 KB (-60.0%, DSSIM: 0.00166036)

credits: Jeff Sheldon, via Unsplash

avif

Original Original
725 KB

Optimized Optimized
194 KB (-73.2%, DSSIM: 0.00163751)

credits: Jeff Sheldon, via Unsplash

png

Original: Photoshop 'Save for web' | PNG-24 with transparency
39 KB

Original

Optimized
16 KB (-59%, DSSIM: 0.00000251)

Optimized

svg

Original: Illustrator | Web optimized SVG export
25 KB

Original

Optimized
20 KB (-21.5%)

Optimized

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package (it's MIT-licensed), but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

This package has been inspired by psliwa/image-optimizer

Emotional support provided by Joke Forment

License

The MIT License (MIT). Please see License File for more information.

image-optimizer's People

Contributors

0xb4lint avatar a3020 avatar adrianmrn avatar ahtinurme avatar akoepcke avatar brendt avatar dependabot[bot] avatar erikn69 avatar exussum12 avatar freekmurze avatar github-actions[bot] avatar itsgoingd avatar jan-tricks avatar javiereguiluz avatar johanleroux avatar jpuck avatar l-alexandrov avatar mansoorkhan96 avatar melbahja avatar mrpropre avatar n3vrax avatar neok avatar nielsvanpach avatar patinthehat avatar peter279k avatar rubenvanassche avatar sebastiandedeyne avatar shuvroroy avatar tangrufus avatar willemvb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

image-optimizer's Issues

wp image-optimize find /path/to/my/directory --extensions=gif,jpeg,jpg,png,svg

I've tried every way I can think of to get this command to work:

wp image-optimize find /path/to/my/directory --extensions=gif,jpeg,jpg,png,svg

but I keep getting the fatal error.

I'm using Xampp on PC. all other commands seem to work, but this one... no luck. Is there some trick to setting the file path that I'm missing?

This code error

Please help me. Code this error
File: src/OptimizerChainFactory.php
line 13: public static function create(): OptimizerChain

Problem with Intervention\Image or \Imagick

After running the ImageOptimizer::optimize and then trying to open it with \Imagick (or Intervention\Image with the imagick driver) I get no php error, but nginx returns a 502 Gateway error.
The file is optimised, but basically opening the optomized jpg file with \Imagick errors fatally.

Does anyone have a idea how to debug this? Nginx does not log any error, even when I switch error reporting onto "info" and laravel only logs the debug from ImageOptimizer, which looks fine (as the image is optomized, I am assuming this is more of a crash issue with \Imagick that cannot handle the optomized image).

Test System: Recent Laravel Homestead, Ubuntu, Nginx, PHP7.1. etc.

Macos PHP71 doesn't work

Hi guys!
How can your lib be working in php71 on MacosX?
Can you please let me know why this is happening? Just followed your guide.

Slow compression

I installed this library with Laravel 6 and the compression time is a quite slow, between 25 and 40 seconds per image.
I have some question about it.

  • Its normal?
  • I need compress the images with a task?
  • What impact have the server if I make it in a task, the website will be affected?
  • Whats the recommended CPU/Ram specs?

The site have a dropzone where each client can upload a max of 300 photos, I want optimize the images to save disk space and gain page speed on browser image load.

Its my local specs

Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz
MemTotal: 957408 kB
MemFree: 88340 kB
MemAvailable: 115412 kB

setBinaryPath on OSX (or any system really)

I have a package that is utilizing image-optimizer and I want to detect if the optimizers are present on the system. On my local machine I've installed all of them but binaryPath is an empty string. I had assumed that if that path was empty they were not present. Maybe that's incorrect?

Do I need to do something more to point image-optimizer to those binaries?

In this case the libs are installed with brew as mentioned in the documentation.

images can't optimize as much as your examples

Hello, I'm trying to get similar results as you saved 525 KB (95%)

on jpeg but it only reduce the value to 238kb

I set value to '-m60', as your example

but I couldn't get 95% result

how can I get same results as your tests

Kb is wrong, It is KB.

The readme documentation suggest wrong Unit for measuring the size of file. KB stands for Kilo Byte while Kb stands for Kilo bits

Error executing commands on windows

it seems placing the binary name between single quotes does not work, at least on windows
it gives command not found

public function getCommand(): string
{
    $optionString = implode(' ', $this->options);
    return "'{$this->binaryName}' {$optionString} ".escapeshellarg($this->imagePath);
}

Maybe should stick to double quotes instead, that seem to work on the command line

Problem when install image-optimizer Conclusion: don't install spatie/image-optimizer 1.0.9

here is error:

composer require spatie/image-optimizer

Using version ^1.0 for spatie/image-optimizer
./composer.json has been updated

php artisan clear-compiled

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Conclusion: don't install spatie/image-optimizer 1.0.9
- Conclusion: don't install spatie/image-optimizer 1.0.8
- Conclusion: don't install spatie/image-optimizer 1.0.7
- Conclusion: don't install spatie/image-optimizer 1.0.6
- Conclusion: don't install spatie/image-optimizer 1.0.5
- Conclusion: don't install spatie/image-optimizer 1.0.4
- Conclusion: don't install spatie/image-optimizer 1.0.3
- Conclusion: don't install spatie/image-optimizer 1.0.1
- Installation request for spatie/image-optimizer ^1.0 -> satisfiable by spatie/image-optimizer[1.0.0, 1.0.1, 1.0.3, 1.0.4, 1.0.5, 1.0.6, 1.0.7, 1.0.8, 1.0.9].
- Conclusion: remove symfony/process v2.7.5
- spatie/image-optimizer 1.0.0 requires symfony/process ^3.3 -> satisfiable by symfony/process[v3.3.0, v3.3.1, v3.3.10, v3.3.2, v3.3.3, v3.3.4, v3.3.5, v3.3.6, v3.3.7, v3.3.8, v3.3.9].
- Can only install one of: symfony/process[v3.3.0, v2.7.5].
- Can only install one of: symfony/process[v3.3.1, v2.7.5].
- Can only install one of: symfony/process[v3.3.10, v2.7.5].
- Can only install one of: symfony/process[v3.3.2, v2.7.5].
- Can only install one of: symfony/process[v3.3.3, v2.7.5].
- Can only install one of: symfony/process[v3.3.4, v2.7.5].
- Can only install one of: symfony/process[v3.3.5, v2.7.5].
- Can only install one of: symfony/process[v3.3.6, v2.7.5].
- Can only install one of: symfony/process[v3.3.7, v2.7.5].
- Can only install one of: symfony/process[v3.3.8, v2.7.5].
- Can only install one of: symfony/process[v3.3.9, v2.7.5].
- Installation request for symfony/process == 2.7.5.0 -> satisfiable by symfony/process[v2.7.5].

Installation failed, reverting ./composer.json to its original content.

"php": ">=5.5.9",
"laravel/framework": "5.1.*",

can you down support for laravel 5.1, thank

Faulty image optimization with Pngquant 2.12.5

I'm having some issues with the recent Pngquant version 2.12.5.
Previously we've used version 2.7.2 without any issues.

Original Image:
Schermafbeelding 2019-09-17 om 14 18 37

After optimization with Pngquant:
Schermafbeelding-2019-09-17-om-14 18 37

As you can see this results in a bitmap like image.

For now i've bypassed the issue by removing Pngquant.
Optipng works good as it always did.

PHP warning 16384: Passing a command as string when creating a "Symfony\Component\Process\Process" instance is deprecated

Hello,

Can you fix this deprecation warning at OptimizerChain.php (line 97): https://github.com/spatie/image-optimizer/blob/master/src/OptimizerChain.php#L97?

Passing a command as string when creating a "Symfony\Component\Process\Process" instance is deprecated since Symfony 4.2, pass it as an array of its arguments instead, or use the "Process::fromShellCommandline()" constructor if you need features provided by the shell.

Trace:

[
   ...,
    {
        "file": "........\/vendor\/symfony\/process\/Process.php",
        "line": 147,
        "function": "trigger_error",
        "args": [
            "Passing a command as string when creating a \"Symfony\\Component\\Process\\Process\" instance is deprecated since Symfony 4.2, pass it as an array of its arguments instead, or use the \"Process::fromShellCommandline()\" constructor if you need features provided by the shell.",
            16384
        ]
    },
    {
        "file": ".......\/vendor\/spatie\/image-optimizer\/src\/OptimizerChain.php",
        "line": 97,
        "function": "__construct",
        "class": "Symfony\\Component\\Process\\Process",
        "type": "->",
        "args": [
            "\"jpegoptim\" -m85 --strip-all --all-progressive '\/tmp\/phpOiNlUf'"
        ]
    },
   ...
]

Laravel 5.1 compatibility

Great work on this package guys! I absolutely love it!

I'd really like to use it in a Laravel 5.1 LTS project I'm working on, but I can't because of the dependencies. Laravel 5.1 uses symfony/process 2.7.* while image-optimizer requires ^2.8.

Is there any way ^2.7 could be added to be compatible with 5.1? Or would that break stuff on your end?

Your requirements could not be resolved to an installable set of packages.

Hi,

When i try to install the package i get the following error.

PS C:\xampp\htdocs> composer require spatie/image-optimizer
Using version ^1.0 for spatie/image-optimizer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Conclusion: don't install spatie/image-optimizer 1.0.7
- Conclusion: don't install spatie/image-optimizer 1.0.6
- Conclusion: don't install spatie/image-optimizer 1.0.5
- Conclusion: don't install spatie/image-optimizer 1.0.4
- Conclusion: don't install spatie/image-optimizer 1.0.3
- Conclusion: don't install spatie/image-optimizer 1.0.1
- Conclusion: remove symfony/process v2.7.29
- Installation request for spatie/image-optimizer ^1.0 -> satisfiable by spatie/image-optimizer[1.0.0, 1.0.1, 1.0.3, 1.0.4, 1.0.5, 1.0.6, 1.0.7].
- Conclusion: don't install symfony/process v2.7.29
- spatie/image-optimizer 1.0.0 requires symfony/process ^3.3 -> satisfiable by symfony/process[v3.3.0, v3.3.1, v3.3.2, v3.3.3, v3.3.4, v3.3.5, v3.3.6].
- Can only install one of: symfony/process[v3.3.0, v2.7.29].
- Can only install one of: symfony/process[v3.3.1, v2.7.29].
- Can only install one of: symfony/process[v3.3.2, v2.7.29].
- Can only install one of: symfony/process[v3.3.3, v2.7.29].
- Can only install one of: symfony/process[v3.3.4, v2.7.29].
- Can only install one of: symfony/process[v3.3.5, v2.7.29].
- Can only install one of: symfony/process[v3.3.6, v2.7.29].
- Installation request for symfony/process (locked at v2.7.29) -> satisfiable by symfony/process[v2.7.29].

Installation failed, reverting ./composer.json to its original content.

i use laravel: 5.1

'jpegoptim' is not recognized as an internal or external command

I have the following error in my log:

[2019-09-17 19:17:01] optimize_error.ERROR: Process errored with '"jpegoptim"' is not recognized as an internal or external command, operable program or batch file. [] []

And i follow the documentation to use this optimizer:

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain
  ->useLogger(new Logger('optimize_error'))
  ->optimize($file->getPathName());

I can execute jpegoptim command in my cmd but not in php..

I am using window 10 x64bit and xampp.

Any solution?

Symphony Process version trouble

Please decrease or fix the required symfony/process package version to ~3.0 or similar to match your PHP7.0 version constraint. The version 4.0.x requires PHP7.1.

Timeout Error

Occasionally I get this error:

Uncaught Symfony\Component\Process\Exception\ProcessTimedOutException: The process ""jpegoptim" -m85 --strip-all --all-progressive $file exceeded the timeout of 30 seconds. in vendor/symfony/process/Process.php:1236

would a try/catch around $process->run() in spatie/image-optimizer/src/OptimizerChain.php be the correct way to handle it? *edit: no that didn't help

Thanks

edit:
I wrapped my request in try catch and now its working as expected.

Overriding binaries

Hello,

Would it be possible to use a configuration file to specify the binaries or something? Currently these are coded into each class as something that's expected to be in the PATH for either windows/*nix users.

It would be helpful to be able to override it.

Thanks

Conclusion: remove symfony/process v3.1.10

Hi i have the following error: if someone can help me with

โžœ (master) composer require spatie/image-optimizer
Using version ^1.0 for spatie/image-optimizer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install spatie/image-optimizer 1.0.6
    - Conclusion: don't install spatie/image-optimizer 1.0.5
    - Conclusion: don't install spatie/image-optimizer 1.0.4
    - Conclusion: don't install spatie/image-optimizer 1.0.3
    - Conclusion: don't install spatie/image-optimizer 1.0.1
    - Conclusion: remove symfony/process v3.1.10
    - Installation request for spatie/image-optimizer ^1.0 -> satisfiable by spatie/image-optimizer[1.0.0, 1.0.1, 1.0.3, 1.0.4, 1.0.5, 1.0.6].
    - Conclusion: don't install symfony/process v3.1.10
    - spatie/image-optimizer 1.0.0 requires symfony/process ^3.3 -> satisfiable by symfony/process[v3.3.0, v3.3.1, v3.3.2, v3.3.3, v3.3.4, v3.3.5].
    - Can only install one of: symfony/process[v3.3.0, v3.1.10].
    - Can only install one of: symfony/process[v3.3.1, v3.1.10].
    - Can only install one of: symfony/process[v3.3.2, v3.1.10].
    - Can only install one of: symfony/process[v3.3.3, v3.1.10].
    - Can only install one of: symfony/process[v3.3.4, v3.1.10].
    - Can only install one of: symfony/process[v3.3.5, v3.1.10].
    - Installation request for symfony/process (locked at v3.1.10) -> satisfiable by symfony/process[v3.1.10].
  • PHP 7
  • "laravel/framework": "5.3.*",

Parse error syntax error unexpected ?

OS Ubuntu 16.04
PHP Version 7.1.16
Web Server Nginx 1.10.3

My code

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'vendor/autoload.php';

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

$pathToImage = "test.jpg";
$pathToOutput = "test_1.jpg";

$optimizerChain->optimize($pathToImage, $pathToOutput);
?>

It appears error

Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE) in /var/www/html/opt/vendor/symfony/process/Process.php on line 139

what can I do?

Pngquant isn't using binary path config value.

Spatie\ImageOptimizer\Optimizers\Pngquant overrides Spatie\ImageOptimizer\Optimizers\BaseOptimizer::getCommand() with a command that doesn't use the binaryPath configuration value.

    public function getCommand(): string
    {
        $optionString = implode(' ', $this->options);
        return "{$this->binaryName} {$optionString}"
            .' '.escapeshellarg($this->imagePath)
            .' --output='.escapeshellarg($this->imagePath);
    }

should be

    public function getCommand(): string
    {
        $optionString = implode(' ', $this->options);

        return "\"{$this->binaryPath}{$this->binaryName}\" {$optionString}"
            .' '.escapeshellarg($this->imagePath)
            .' --output='.escapeshellarg($this->imagePath);
    }

How to upload multiple images after preview and change sequence of images using jquery and php?

Hi,
This is milind and i post issue on github first time, so please try to understand my some spelling mistake and issue explaination.

I had make file upload module using jquery and php. There can user preview and change sequence of selected images before upload. Here that madule work done. But i cant understand how images upload after change sequeance and preview of images. I attached whole code for your referance.

index.zip

Thanks.

Laravel Mix?

This migth be a little soon, but It'd be cool to integrate this into Laravel Mix and auto-optimize images.

Class 'Spatie\ImageOptimizer\OptimizerChainFactory'

I'm using it with Laravel 6. In a service I'm initializing OptimizerChainFactory but getting class not found error. I've run cache:clear command. Composer dump-autoload command but to no avail.
It runs alright in a separate directory where its also installed through composer.
Any suggestions

how to use this package with spatie/laravel-glide ?

Hello!
in my project I use glide this way:

use League\Glide\ServerFactory;
use League\Glide\Responses\LaravelResponseFactory;
Route::get('glide/{path}', function($path) {
    $server = ServerFactory::create([
        'response' => new LaravelResponseFactory(app('request')),
        'source' => app('filesystem')->disk('public')->getDriver(),
        'cache' => storage_path('glide'),
    ]);
    return $server->getImageResponse($path, Input::query());
})->where('path', '.+');

Tell me, please, how can I integrate a spatie / image-optimizer into this scheme?

Issue on Azure

Package fails on Azure due to some unknown problem with "Symfony\Process".

Unfortunately the only message which I'm getting is
The page cannot be displayed because an internal server error has occurred.

Nothing in the Azure IIS and PHP logs.

Not sure what to suggest but maybe some detection that if on Azure / Windows then simply run "exec" instead of creating "Process" instance.

Custom SVGO optimizer not running as expexted with symfony/process 3.4.4

I've created a custom SVGO optimizer:

<?php

namespace SotPlate\Optimizers;

use Spatie\ImageOptimizer\Image;
use Spatie\ImageOptimizer\Optimizers\Svgo;

class CustomSvgo extends Svgo
{
    public $binaryName = 'npm run svgo --';

    public $options = [
        '--disable=cleanupIDs',
        '--enable=removeTitle',
        '--disable=removeStyleElement', // some colored logos rely on style-tag
        '--enable=removeScriptElement',
        '--enable=removeEmptyContainers',
    ];

    public function __construct($options = [])
    {
        $this->setOptions($this->options);
    }

    public function canHandle(Image $image): bool
    {
        var_dump($image->extension());
        var_dump($image->mime());
        if ($image->extension() !== 'svg' && $image->extension() !== 'tmp') {
            return false;
        }

        return $image->mime() === 'text/html' || $image->mime() === 'image/svg+xml';
    }
}

... which I'm triggering in Wordpress like this:

use Spatie\ImageOptimizer\OptimizerChain;
use SotPlate\Optimizers\CustomSvgo;
add_filter('wp_handle_upload_prefilter', function ( $file ) {
    if ($file['type'] !== 'image/svg+xml' ) {
        return $file;
    }

    // run svgo on uploaded file
    $svgo = new CustomSvgo();
    $optimizerChain =
                    (new OptimizerChain)
                    ->addOptimizer($svgo)
                    ->optimize($file["tmp_name"]);

    return $file;
});

With this added to my package.json:

{
    "scripts": {
        "svgo": "cross-env NODE_ENV=production node_modules/svgo/bin/svgo"
    }
}

I'm using this in my boilerplate for most of my new projects. Recently this stopped working (i.e. the svgo command is never run, or at least the optimized results are not saved back to the uploaded file).
spatie/image-optimizer version is the same, but the symfony/process versions aren't. The above works with symfony/process version 3.4.0 but not with 3.4.4.

The only difference in output when dumping $process last in OptimizerChain::applyOptimizer() seems to be

object(Symfony\Component\Process\Process)#7166 (29) {
  ["processPipes":"Symfony\Component\Process\Process":private]=>
  object(Symfony\Component\Process\Pipes\WindowsPipes)#7168 (8) {
    ["files":"Symfony\Component\Process\Pipes\WindowsPipes":private]=>
    array(2) {
      [1]=>
      string(30) "C:\WINDOWS\TEMP\sf_proc_00.out"
      [2]=>
      string(30) "C:\WINDOWS\TEMP\sf_proc_00.err"
    }
}

when working, and

object(Symfony\Component\Process\Process)#7166 (29) {
  ["processPipes":"Symfony\Component\Process\Process":private]=>
  object(Symfony\Component\Process\Pipes\WindowsPipes)#7168 (8) {
    ["readBytes":"Symfony\Component\Process\Pipes\WindowsPipes":private]=>
    array(2) {
      [1]=>
      int(0)
      [2]=>
      int(1424)
    }
}

when not working. (I'm omitting identical output for the two cases of $process above.)

I'm guessing of course that is an issue with symfony/process and not this package, but my knowledge of these two packages are limited, so I'm asking here first hoping someone at least can point me in the right direction. :)

I'm running Windows 10 and Apache for the above. I haven't tested this with the regular Spatie\ImageOptimizer\Optimizers\Svgo, but I'm guessing the outcome will be the same.

Gist available for bulk recursive image optimization

Hello,

Thanks for your wonderful image optimizer. No bug, it works like a charm.

I created this GIST to make a recursive bulk image optimization with image-optimizer: https://gist.github.com/migliori/69e86e5ec6488c73c50d7f87fdd207db

The optimization is made from a parent images folder. It optimizes all the images found recursively in all its subdirecories without deph limitation.

A single click launches the process. All is done with Ajax.
Tested with 5000+ images, optimized successfully in a few minutes.

I thought it may be useful for other users.

I do not see the image is optimized

Hi admin,
I use file image at for test . I do not see it reduced in size (optimizer). Please help me
`<?php
include('vendor/autoload.php');
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();

$pathToImage = 'C:\xampp\htdocs\image\1.png';
$test = $optimizerChain->optimize($pathToImage);`

TinyPNG integration

This might be a bit too soon, but wanted to check if it's a good idea to integrate external services too. Let's say you don't have the necessary optimizers installed on the system, but you can still have the option to add your api key and let TinyPNG/TinyJPG optimize the images.

I'm currently using their developer api in a CMS image optimization module I wrote, but would love to swap the custom code out by your library so I can also support the other system optimizers if there are any on the system, and I believe many others would benefit from TinyPNG too.

With TinyPNG you get 500 images for free which is plenty for most of my use cases (and other users) + They do a really good job on compression (and can even crop/resize and do area-of-interest detection but that's not the goal of this package).

Not changing size?

Hey having some trouble, doesn't seem to be changing my file size, original is 761kb and fixed is still 761kb

On one of my controllers:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$pathToOptimizedImage = 'images/uploads/fixed.png'; $pathToImage = 'images/uploads/download.png'; $optimizerChain = OptimizerChainFactory::create(); $optimizerChain ->optimize($pathToImage, $pathToOptimizedImage);

Image Not Comprime

hi , this is my code :
$files = scandir('_xeo/_opt/');
foreach($files as $file) {
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($file);
var_dump($optimizerChain);
}
the images that are within the cycle, weigh like the original ones, do not understand why, the class seems to be loaded correctly.
the packages have been installed inside the server but we do not understand why this library is still not working, waiting for an answer Sincerely ๐Ÿ‘

Should we considered with `imagedestroy`?

In the Laravel's queue documentation (in Resource Consideration), it's mention that we should perform imagedestroy after optimizing the image, when we're using queue.

Daemon queue workers do not "reboot" the framework before processing each job. Therefore, you should free any heavy resources after each job completes. For example, if you are doing image manipulation with the GD library, you should free the memory with imagedestroy when you are done.

Should the imagedestroy implemented by default in this package?

Amazon Linux EC2 Support?

Due to the requirement of jpegoptim EC2 Amazon Linux distro doesn't have this. And it's not part of their package of yum installs. Doing manually can't happen because it also requires a newer version of libjpeg which it believes is already on the latest version in the distro. I was not able to successfully get this working due to jpegoptim issues.

Error, image not found.

Hello there, i keep getting image not found, pretty sure its my buggy code, nothing to do with the library itself, here is how am doing it;

$path = $request->file('cover_image')->storeAs('public/images/'.$post->time.'/', $fileNameToStore);
$optimizerChain->setTimeout(10)->optimize($path);

Help appreciated, thank you.

Process errored with "sh: jpegoptim: command not found"

Do you have any suggestions on what to do if this error occurs?

Process errored with `sh: jpegoptim: command not found`}

macOS 10.12.6, PHP 7.1, Apache 2.4.

brew list shows jpegoptim.

If I open the terminal and enter jpegoptim, the command works as expected.

The same problem occurs for the other optimizers. Is there something wrong in my PHP configuration?

phpdoc

Hello,

you can understand this issue as a little question, i've tried to review your code and one thing is there, what i can't understand :) Why you don't use phpdoc ? It would be much better, especially for IDE Support.

Thank you for all your work!

Optimizes images locally, but not in production?

I have jpegoptim installed on the server, but it's not doing anything.

Is there anything else that needs to be installed in order for this to work? Could there be a permission issue?

The server is running CentOS.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.