{"id":13518319,"url":"https://github.com/spatie/image-optimizer","last_synced_at":"2025-05-14T07:07:57.672Z","repository":{"id":37852441,"uuid":"96041872","full_name":"spatie/image-optimizer","owner":"spatie","description":"Easily optimize images using PHP","archived":false,"fork":false,"pushed_at":"2025-01-27T18:39:17.000Z","size":7888,"stargazers_count":2779,"open_issues_count":0,"forks_count":222,"subscribers_count":57,"default_branch":"main","last_synced_at":"2025-04-22T06:21:00.646Z","etag":null,"topics":["gif","image","jpeg","optimizer","performance","php","png"],"latest_commit_sha":null,"homepage":"https://freek.dev/797-easily-optimize-images-using-php-and-some-binaries","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-02T18:33:09.000Z","updated_at":"2025-04-18T21:09:12.000Z","dependencies_parsed_at":"2023-02-16T10:10:28.098Z","dependency_job_id":"39ee4c8c-f83c-430a-bdb8-d0cb49cc2d3a","html_url":"https://github.com/spatie/image-optimizer","commit_stats":{"total_commits":320,"total_committers":46,"mean_commits":6.956521739130435,"dds":0.46875,"last_synced_commit":"4b9993e162dbc3a4e3aff03e3deebd3f0fb077f4"},"previous_names":[],"tags_count":44,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fimage-optimizer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fimage-optimizer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fimage-optimizer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fimage-optimizer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/image-optimizer/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250246778,"owners_count":21398926,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["gif","image","jpeg","optimizer","performance","php","png"],"created_at":"2024-08-01T05:01:43.534Z","updated_at":"2025-04-22T13:22:53.064Z","avatar_url":"https://github.com/spatie.png","language":"PHP","readme":"# Easily optimize images using PHP\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/image-optimizer.svg?style=flat-square)](https://packagist.org/packages/spatie/image-optimizer)\n![Tests](https://github.com/spatie/image-optimizer/workflows/Tests/badge.svg)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/image-optimizer.svg?style=flat-square)](https://packagist.org/packages/spatie/image-optimizer)\n\nThis package can optimize PNGs, JPGs, WEBPs, AVIFs, SVGs and GIFs by running them through a chain of various [image optimization tools](#optimization-tools). Here's how you can use it:\n\n```php\nuse Spatie\\ImageOptimizer\\OptimizerChainFactory;\n\n$optimizerChain = OptimizerChainFactory::create();\n\n$optimizerChain-\u003eoptimize($pathToImage);\n```\n\nThe 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.\n\nHere are some [example conversions](#example-conversions) that have been done by this package.\n\nLoving Laravel? Then head over to [the Laravel specific integration](https://github.com/spatie/laravel-image-optimizer).\n\nUsing WordPress? Then try out [the WP CLI command](https://github.com/TypistTech/image-optimize-command).\n\nSilverStripe enthusiast? Don't waste time, go to [the SilverStripe module](https://github.com/axllent/silverstripe-image-optimiser).\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/image-optimizer.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/image-optimizer)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).\n\nWe 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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require spatie/image-optimizer\n```\n\n### Optimization tools\n\nThe package will use these optimizers if they are present on your system:\n\n- [JpegOptim](https://github.com/tjko/jpegoptim)\n- [Optipng](http://optipng.sourceforge.net/)\n- [Pngquant 2](https://pngquant.org/)\n- [SVGO 1](https://github.com/svg/svgo)\n- [Gifsicle](http://www.lcdf.org/gifsicle/)\n- [cwebp](https://developers.google.com/speed/webp/docs/precompiled)\n- [avifenc](https://github.com/AOMediaCodec/libavif/blob/main/doc/avifenc.1.md)\n\nHere's how to install all the optimizers on Ubuntu/Debian:\n\n```bash\nsudo apt-get install jpegoptim\nsudo apt-get install optipng\nsudo apt-get install pngquant\nsudo npm install -g svgo\nsudo apt-get install gifsicle\nsudo apt-get install webp\nsudo apt-get install libavif-bin # minimum 0.9.3\n```\n\nAnd here's how to install the binaries on MacOS (using [Homebrew](https://brew.sh/)):\n\n```bash\nbrew install jpegoptim\nbrew install optipng\nbrew install pngquant\nnpm install -g svgo\nbrew install gifsicle\nbrew install webp\nbrew install libavif\n```\n\nAnd here's how to install the binaries on Fedora/RHEL/CentOS:\n\n```bash\nsudo dnf install epel-release\nsudo dnf install jpegoptim\nsudo dnf install optipng\nsudo dnf install pngquant\nsudo npm install -g svgo\nsudo dnf install gifsicle\nsudo dnf install libwebp-tools\nsudo dnf install libavif-tools\n```\n\n## Which tools will do what?\n\nThe package will automatically decide which tools to use on a particular image.\n\n### JPGs\n\nJPGs will be made smaller by running them through [JpegOptim](http://freecode.com/projects/jpegoptim). These options are used:\n- `-m85`: this will store the image with 85% quality. This setting [seems to satisfy Google's Pagespeed compression rules](https://webmasters.stackexchange.com/questions/102094/google-pagespeed-how-to-satisfy-the-new-image-compression-rules)\n- `--strip-all`: this strips out all text information such as comments and EXIF data\n- `--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.\n\n### PNGs\n\nPNGs will be made smaller by running them through two tools. The first one is [Pngquant 2](https://pngquant.org/), a lossy PNG compressor. We set no extra options, their defaults are used. After that we run the image through a second one: [Optipng](http://optipng.sourceforge.net/). These options are used:\n- `-i0`: this will result in a non-interlaced, progressive scanned image\n- `-o2`: this set the optimization level to two (multiple IDAT compression trials)\n\n### SVGs\n\nSVGs will be minified by [SVGO](https://github.com/svg/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.\n\nPlease be aware that SVGO can break your svg. You'll find more info on that in this [excellent blogpost](https://www.sarasoueidan.com/blog/svgo-tools/) by [Sara Soueidan](https://twitter.com/SaraSoueidan).\n\n### GIFs\n\nGIFs will be optimized by [Gifsicle](http://www.lcdf.org/gifsicle/). These options will be used:\n- `-O3`: this sets the optimization level to Gifsicle's maximum, which produces the slowest but best results\n\n### WEBPs\n\nWEBPs will be optimized by [Cwebp](https://developers.google.com/speed/webp/docs/cwebp). These options will be used:\n- `-m 6` for the slowest compression method in order to get the best compression.\n- `-pass 10` for maximizing the amount of analysis pass.\n- `-mt` multithreading for some speed improvements.\n- `-q 90` Quality factor that brings the least noticeable changes.\n\n(Settings are original taken from [here](https://medium.com/@vinhlh/how-i-apply-webp-for-optimizing-images-9b11068db349))\n\n### AVIFs\n\nAVIFs will be optimized by [avifenc](https://github.com/AOMediaCodec/libavif/blob/main/doc/avifenc.1.md). These options will be used:\n- `-a cq-level=23`: Constant Quality level. Lower values mean better quality and greater file size (0-63).\n- `-j all`: Number of jobs (worker threads, `all` uses all available cores).\n- `--min 0`: Min quantizer for color (0-63).\n- `--max 63`: Max quantizer for color (0-63).\n- `--minalpha 0`: Min quantizer for alpha (0-63).\n- `--maxalpha 63`: Max quantizer for alpha (0-63).\n- `-a end-usage=q` Rate control mode set to Constant Quality mode.\n- `-a tune=ssim`: SSIM as tune the encoder for distortion metric.\n\n(Settings are original taken from [here](https://web.dev/compress-images-avif/#create-an-avif-image-with-default-settings) and [here](https://github.com/feat-agency/avif))\n\n## Usage\n\nThis is the default way to use the package:\n\n``` php\nuse Spatie\\ImageOptimizer\\OptimizerChainFactory;\n\n$optimizerChain = OptimizerChainFactory::create();\n\n$optimizerChain-\u003eoptimize($pathToImage);\n```\n\nThe image at `$pathToImage` will be overwritten by an optimized version which should be smaller.\n\nThe package will automatically detect which optimization binaries are installed on your system and use them.\n\nTo keep the original image, you can pass through a second argument`optimize`:\n```php\nuse Spatie\\ImageOptimizer\\OptimizerChainFactory;\n\n$optimizerChain = OptimizerChainFactory::create();\n\n$optimizerChain-\u003eoptimize($pathToImage, $pathToOutput);\n```\n\nIn that example the package won't touch `$pathToImage` and write an optimized version to `$pathToOutput`.\n\n### Setting a timeout\n\nYou can set the maximum of time in seconds that each individual optimizer in a chain can use by calling `setTimeout`:\n\n```php\n$optimizerChain\n    -\u003esetTimeout(10)\n    -\u003eoptimize($pathToImage);\n```\n\nIn this example each optimizer in the chain will get a maximum 10 seconds to do it's job.\n\n### Creating your own optimization chains\n\nIf you want to customize the chain of optimizers you can do so by adding `Optimizer`s manually to an `OptimizerChain`.\n\nHere's an example where we only want `optipng` and `jpegoptim` to be used:\n\n```php\nuse Spatie\\ImageOptimizer\\OptimizerChain;\nuse Spatie\\ImageOptimizer\\Optimizers\\Jpegoptim;\nuse Spatie\\ImageOptimizer\\Optimizers\\Pngquant;\n\n$optimizerChain = (new OptimizerChain)\n   -\u003eaddOptimizer(new Jpegoptim([\n       '--strip-all',\n       '--all-progressive',\n   ]))\n\n   -\u003eaddOptimizer(new Pngquant([\n       '--force',\n   ]))\n```\n\nNotice that you can pass the options an `Optimizer` should use to its constructor.\n\n### Writing a custom optimizers\n\nWant 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:\n\n```php\nnamespace Spatie\\ImageOptimizer\\Optimizers;\n\nuse Spatie\\ImageOptimizer\\Image;\n\ninterface Optimizer\n{\n    /**\n     * Returns the name of the binary to be executed.\n     *\n     * @return string\n     */\n    public function binaryName(): string;\n\n    /**\n     * Determines if the given image can be handled by the optimizer.\n     *\n     * @param \\Spatie\\ImageOptimizer\\Image $image\n     *\n     * @return bool\n     */\n    public function canHandle(Image $image): bool;\n\n    /**\n     * Set the path to the image that should be optimized.\n     *\n     * @param string $imagePath\n     *\n     * @return $this\n     */\n    public function setImagePath(string $imagePath);\n\n    /**\n     * Set the options the optimizer should use.\n     *\n     * @param array $options\n     *\n     * @return $this\n     */\n    public function setOptions(array $options = []);\n\n    /**\n     * Get the command that should be executed.\n     *\n     * @return string\n     */\n    public function getCommand(): string;\n}\n```\n\nIf you want to view an example implementation take a look at [the existing optimizers](https://github.com/spatie/image-optimizer/tree/master/src/Optimizers) shipped with this package.\n\nYou can easily add your optimizer by using the `addOptimizer` method on an `OptimizerChain`.\n\n``` php\nuse Spatie\\ImageOptimizer\\ImageOptimizerFactory;\n\n$optimizerChain = OptimizerChainFactory::create();\n\n$optimizerChain\n   -\u003eaddOptimizer(new YourCustomOptimizer())\n   -\u003eoptimize($pathToImage);\n```\n\n## Logging the optimization process\n\nBy default the package will not throw any errors and just operate silently. To verify what the package is doing you can set a logger:\n\n```php\nuse Spatie\\ImageOptimizer\\OptimizerChainFactory;\n\n$optimizerChain = OptimizerChainFactory::create();\n\n$optimizerChain\n   -\u003euseLogger(new MyLogger())\n   -\u003eoptimize($pathToImage);\n```\n\nA logger is a class that implements `Psr\\Log\\LoggerInterface`. A good logging library that's fully compliant is [Monolog](https://github.com/Seldaek/monolog). The package will write to log which `Optimizers` are used, which commands are executed and their output.\n\n## Example conversions\n\nHere are some real life example conversions done by this package.\n\nMethodology for JPG, WEBP, AVIF images: the [original image](https://unsplash.com/photos/jTeQavJjBDs) has been fed to [spatie/image](https://github.com/spatie/image) (using the default GD driver) and resized to 2048px width:\n\n```php\nSpatie\\Image\\Image::load('original.jpg')\n    -\u003ewidth(2048)\n    -\u003esave('image.jpg'); // image.png, image.webp, image.avif\n```\n\n### jpg\n\n![Original](https://spatie.github.io/image-optimizer/examples/image.jpg)\nOriginal\u003cbr\u003e\n771 KB\n\n![Optimized](https://spatie.github.io/image-optimizer/examples/image-optimized.jpg)\nOptimized\u003cbr\u003e\n511 KB (-33.7%, DSSIM: 0.00052061)\n\ncredits: Jeff Sheldon, via [Unsplash](https://unsplash.com)\n\n### webp\n\n![Original](https://spatie.github.io/image-optimizer/examples/image.webp)\nOriginal\u003cbr\u003e\n461 KB\n\n![Optimized](https://spatie.github.io/image-optimizer/examples/image-optimized.webp)\nOptimized\u003cbr\u003e\n184 KB (-60.0%, DSSIM: 0.00166036)\n\ncredits: Jeff Sheldon, via [Unsplash](https://unsplash.com)\n\n### avif\n\n![Original](https://spatie.github.io/image-optimizer/examples/image.avif)\nOriginal\u003cbr\u003e\n725 KB\n\n![Optimized](https://spatie.github.io/image-optimizer/examples/image-optimized.avif)\nOptimized\u003cbr\u003e\n194 KB (-73.2%, DSSIM: 0.00163751)\n\ncredits: Jeff Sheldon, via [Unsplash](https://unsplash.com)\n\n### png\n\nOriginal: Photoshop 'Save for web' | PNG-24 with transparency\u003cbr\u003e\n39 KB\n\n![Original](https://spatie.github.io/image-optimizer/examples/logo.png)\n\nOptimized\u003cbr\u003e\n16 KB (-59%, DSSIM: 0.00000251)\n\n![Optimized](https://spatie.github.io/image-optimizer/examples/logo-optimized.png)\n\n### svg\n\nOriginal: Illustrator | Web optimized SVG export\u003cbr\u003e\n25 KB\n\n![Original](https://spatie.github.io/image-optimizer/examples/graph.svg)\n\nOptimized\u003cbr\u003e\n20 KB (-21.5%)\n\n![Optimized](https://spatie.github.io/image-optimizer/examples/graph-optimized.svg)\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.\n\n## Testing\n\n``` bash\ncomposer test\n```\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Postcardware\n\nYou're free to use this package (it's [MIT-licensed](.github/LICENSE.md)), 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.\n\nOur address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.\n\nWe publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).\n\n## Credits\n\n- [Freek Van der Herten](https://github.com/freekmurze)\n- [All Contributors](../../contributors)\n\nThis package has been inspired by [psliwa/image-optimizer](https://github.com/psliwa/image-optimizer)\n\nEmotional support provided by [Joke Forment](https://twitter.com/pronneur)\n\n## License\n\nThe MIT License (MIT). Please see [License File](.github/LICENSE.md) for more information.\n","funding_links":[],"categories":["PHP"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fimage-optimizer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Fimage-optimizer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fimage-optimizer/lists"}