Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.

Overview

Image Optimizer Build Status

This library is handy and very easy to use optimizer for image files. It uses optipng, pngquant, jpegoptim, svgo and few more libraries, so before use it you should install proper libraries on your server. Project contains Vagrantfile that defines testing virtual machine with all libraries installed, so you can check Vagrantfile how to install all those stuff.

Thanks to ImageOptimizer and libraries that it uses, your image files can be 10%-70% smaller.

Installation

Using composer:

composer require ps/image-optimizer

Basic usage

$factory = new \ImageOptimizer\OptimizerFactory();
$optimizer = $factory->get();

$filepath = /* path to image */;

$optimizer->optimize($filepath);
//optimized file overwrites original one

Configuration

By default optimizer does not throw any exception, if file can not be optimized or optimizing library for given file is not installed, optimizer will not touch original file. This behaviour is ok when you want to eventually optimize files uploaded by user. When in your use case optimization fault should cause exception, ignore_errors option was created especially for you.

This library is very smart, you do not have to configure paths to all binaries of libraries that are used by ImageOptimizer, library will be looking for those binaries in few places, so if binaries are placed in standard places, it will be found automatically.

Supported options:

  • ignore_errors (default: true)
  • single_optimizer_timeout_in_seconds (default: 60) - useful when you want to have control how long optimizing lasts. For example in some cases optimizing may not be worth when it takes big amount of time. Pass null in order to turn off timeout.
  • output_filepath_pattern (default: %basename%/%filename%%ext%) - destination where optimized file will be stored. By default it overrides original file. There are 3 placehoders: %basename%, %filename% (without extension and dot) and %ext% (extension with dot) which will be replaced by values from original file.
  • execute_only_first_png_optimizer (default: true) - execute the first successful or all png optimizers
  • execute_only_first_jpeg_optimizer (default: true) - execute the first successful or all jpeg optimizers
  • optipng_options (default: array('-i0', '-o2', '-quiet')) - an array of arguments to pass to the library
  • pngquant_options (default: array('--force'))
  • pngcrush_options (default: array('-reduce', '-q', '-ow'))
  • pngout_options (default: array('-s3', '-q', '-y'))
  • advpng_options (default: array('-z', '-4', '-q'))
  • gifsicle_options (default: array('-b', '-O5'))
  • jpegoptim_options (default: array('--strip-all', '--all-progressive'))
  • jpegtran_options (default: array('-optimize', '-progressive'))
  • svgo_options (default: array('--disable=cleanupIDs'))
  • custom_optimizers (default array())
  • optipng_bin (default: will be guessed) - you can enforce paths to binaries, but by default it will be guessed
  • pngquant_bin
  • pngcrush_bin
  • pngout_bin
  • advpng_bin
  • gifsicle_bin
  • jpegoptim_bin
  • jpegtran_bin
  • svgo_bin

You can pass array of options as first argument of ImageOptimizer\OptimizerFactory constructor. Second argument is optionally Psr\LoggerInterface.

$factory = new \ImageOptimizer\OptimizerFactory(array('ignore_errors' => false), $logger);

Supported optimizers

  • default (smart) - it guess file type and choose optimizer for this file type
  • png - chain of optimizers for png files, by default it uses pngquant and optipng. pngquant is lossy optimization
  • jpg - first of two optimizations will be executed: jpegtran or jpegoptim
  • gif - alias to gifsicle
  • pngquant - homepage
  • optipng - homepage
  • pngcrush - homepage
  • pngout - homepage
  • advpng - homepage
  • jpegtran - homepage
  • jpegoptim - homepage
  • gifsicle - homepage
  • svgo - homepage

You can obtain concrete optimizer by passing his name to ImageOptimizer\OptimizerFactory::get method:

//default optimizer is `smart`
$optimizer = $factory->get();

//png optimizer
$pngOptimizer = $factory->get('png');

//jpegoptim optimizer etc.
$jpgOptimizer = $factory->get('jpegoptim');

Custom optimizers

You can easily define custom optimizers:

$factory = new \ImageOptimizer\OptimizerFactory(array('custom_optimizers' => array(
    'some_optimizier' => array(
        'command' => 'some_command',
        'args' => array('-some-flag')
    )
)), $logger);

And then usage:

$customOptimizer = $factory->get('some_optimizier');

I got "All optimizers failed to optimize the file"

Probably you don't have required optimazers installed. Let's have a look at Vagrantfile file in order to see an example how to install those commands.

In order to see all intermediate errors, you can use logger (be default NullLogger is used, so logs are not available):

class StdoutLogger extends \Psr\Log\AbstractLogger { 
    public function log($level, $message, array $context = array()) { 
        echo $message."\n"; 
    }
}

$factory = new \ImageOptimizer\OptimizerFactory(array(), new StdoutLogger());

$factory->get()->optimize('yourfile.jpg');

// and have a look at stdout

License

MIT

Comments
  • Wrong behavior when choosing jpeg optimizer

    Wrong behavior when choosing jpeg optimizer

    When you have installed only jpegoptim on your system there are no ability to optimize your images due to wrong choose algorithm. In documentation you said: "first of two optimizations will be executed: jpegtran or jpegoptim", but in the code:

    $this->optimizers['jpeg'] = $this->optimizers['jpg'] = new ChainOptimizer(array(
                $this->unwrap($this->optimizers['jpegtran']),
                $this->unwrap($this->optimizers['jpegoptim']),
            ), true);
    

    There are new instance of ChainOptimizer with $executeFirst=true and when it optimize (with my comments)

    public function optimize($filepath)
        {
            foreach($this->optimizers as $optimizer) { // get first optimizer (jpegtran) which wasn't installed
                $optimizer->optimize($filepath); // try to optimize image with it
    
                if($this->executeFirst) break; // break due to $this->executeFirst = true
            }
        }
    

    And we have no chance to change the order of optimizers. I can send a pull request for you, but which decision i have to choose: allow user to set up optimizers by hands or check optimizer availability in OS

    opened by n2j7 9
  • Generated command is wrong?

    Generated command is wrong?

    I'm having the following issue on ubuntu (using version 1.0.6):

    Fatal error: Uncaught exception 'ImageOptimizer\Exception\Exception' with message
    'Command failed, return code: 1, command: /usr/bin/jpegtran '-optimize' '-progressive' '-outfile' '/home/koichirose/public_html/dev/system/../assets/images/news/test_image.jpg' '/home/koichirose/public_html/dev/system/../assets/images/news/test_image.jpg' 1> /dev/null 2> /dev/null'
    in /home/koichirose/public_html/dev/vendor/ps/image-optimizer/src/ImageOptimizer/Command.php:46 
    
    Stack trace: #0 /home/koichirose/public_html/dev/vendor/ps/image-optimizer/src/ImageOptimizer/CommandOptimizer.php(29): ImageOptimizer\Command->execute(Array)
    # 1 /home/koichirose/public_html/dev/vendor/ps/image-optimizer/src/ImageOptimizer/ChainOptimizer.php(24): ImageOptimizer\CommandOptimizer->optimize('/home/koichirose/pub...')
    # 2 /home/koichirose/public_html/dev/vendor/ps/image-optimizer/src/ImageOptimizer/SmartOptimizer.php(32): I in /home/koichirose/public_html/dev/vendor/ps/image-optimizer/src/ImageOptimizer/Command.php on line 46
    

    Running the exact same command without quotes from the command line works fine:

    /usr/bin/jpegtran -optimize -progressive -outfile /home/koichirose/public_html/dev/system/../assets/images/news/test_image.jpg /home/koichirose/public_html/dev/system/../assets/images/news/test_image.jpg
    

    I'm running it like this just to test:

    $full_path = '/home/koichirose/public_html/dev/system/../assets/images/news/test_image.jpg';
    $factory = new \ImageOptimizer\OptimizerFactory(array('ignore_errors' => false));
    $optimizer = $factory->get();
    $optimizer->optimize($full_path);
    
    bug 
    opened by koichirose 8
  • Bump psr/log dependency

    Bump psr/log dependency

    I've got a similar problem to #59. Composer fails to install a big project due to some dependency conflict in this package.

    Composer only shows a cryptic message exactly like in the issue instead of providing precise information, however, experimentally I was able to trace it to psr/log version. php-fig/log v1.1.0 has been released recently and this breaks all of our builds.

    There are no BCs between 1.0 and 1.1 so this should be totally safe to bump.

    opened by pinkeen 6
  • What am I doing wrong?

    What am I doing wrong?

    Hi, I followed the example, and nothing is happening. Libraries are loaded OK, but images (jpg for example) are not reducing its size. Is there a way to check if I am doing everything right? My code is:

    error_reporting(E_ALL); ini_set('display_errors', 1); $loader = require DIR.'/../vendor/autoload.php'; $loader->addPsr4('ImageOptimizer\', DIR.'/ImageOptimizer'); $factory = new \ImageOptimizer\OptimizerFactory(array('ignore_errors' => false)); $optimizer = $factory->get(); $filepath = 'imagen.jpg'; $optimizer->optimize($filepath); //optimized file overwrites original one

    Then, I get the following error: "Fatal error: Uncaught exception 'ImageOptimizer\Exception\Exception' with message 'All optimizers failed to optimize the file: imagen.jpg' "

    Thanks in advance!

    opened by franciscoortiz16 6
  • "Command not found" and open_basedir

    get "Command not found" error when use open_basedir restriction.

    cannot use is_executable when open_basedir path defined and executable optimizer outside of that path.

    to_investigate 
    opened by Junker 6
  • Command not found

    Command not found

    I ran the following command on the server: sudo apt-get install optipng pngquant pngcrush gifsicle jpegoptim I ran the example as stated with the ignore_errors flag set to false but I keep getting command not found.

    opened by omarsafwany 5
  • Showing psr/log installation error with laravel 5.7

    Showing psr/log installation error with laravel 5.7

    I am trying to install in laravel 5.7 but its showing psr/log error and not supporting latest psr/log package.

    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - Installation request for ps/image-optimizer ^1.2 -> satisfiable by ps/imag   e-optimizer[1.2.0].
        - Conclusion: remove psr/log 1.1.0
        - Conclusion: don't install psr/log 1.1.0
        - ps/image-optimizer 1.2.0 requires psr/log 1.0.* -> satisfiable by psr/log[1.0.0, 1.0.1, 1.0.2].
        - Can only install one of: psr/log[1.0.0, 1.1.0].
        - Can only install one of: psr/log[1.0.1, 1.1.0].
        - Can only install one of: psr/log[1.0.2, 1.1.0].
        - Installation request for psr/log (locked at 1.1.0) -> satisfiable by psr/log[1.1.0].
    
    
    Installation failed, reverting ./composer.json to its original content.
    
    opened by umairali 4
  • Document breaking change

    Document breaking change

    This change is breaking and should be added to changelog.

    I also suggest keeping backward compatibility, constructor can look like:

    public function __construct(array $optimizers, $executeFirst = false, LoggerInterface $logger = null)
    

    Which would not break all project that depends on this package. I upgraded (1.0.6 => 1.1.2) and errors started popping.

    opened by umpirsky 4
  • PHP8 Support

    PHP8 Support

    This PR adds support for PHP8.

    I had to update PHPUnit, and bump the PHP 7 compatibility to 7.3 instead of 7.1, so this would need a major release.

    Tests are passing in my testing.

    opened by ThibaultVlacich 3
  • Optimization doesn't work

    Optimization doesn't work

    Hello, can you help me? I installed your library using composer, installed all libraries (optipng, etc.), wrote $factory = new \ImageOptimizer\OptimizerFactory(array('ignore_errors' => false)); But file is not optimized. I tried: $filepath = 'Upload/'.$data['name']; try { $optimizer->optimize($filepath); } catch (CommandNotFound $e) { echo "string"; }

    But 'echo "string";' doesn't appear on my screen.

    opened by TheSDTM 3
  • How to specify quality of the image

    How to specify quality of the image

    Hi, thanks for the awesome library. I'm using jpegoptim. i want to specify the quality of the image when optimizing. Currently arguments are set to --strip-all, --all-progressive. is there a way I can specify the arguments for jpegoptim?

    Thanks

    opened by janakaonline 3
  • How do I install a driver on my local system

    How do I install a driver on my local system

    The repository includes a vagrant file for installing all the drivers. However, I'm developing on my PC and can't port entire project to vagrant just cuz of this. I downloaded the binary pngquant from their site, added its folder to system variables path every but I still get the error regardless. How do I go about this?

    opened by nmeri17 0
  • bug fix path in windows

    bug fix path in windows

    windows have different characters for the directory separator when we run the optimizer on windows sometimes $outputChanaged will be true and the original image will be deleted

    opened by mbpcoder 1
  • Add method to check if optimizers are installed

    Add method to check if optimizers are installed

    This PR adds a checkOptimizers() method that returns an array of all defined optimizers and whether or not they're installed. This is useful, for example, when displaying a configuration page explaining what needs to be installed for certain image types to compress correctly.

    I had to make some private fields public for this to work.

    Example usage:

    $factory = new \ImageOptimizer\OptimizerFactory();
    print_r($factory->checkOptimizers());
    
    Array
    (
        [/usr/local/bin/optipng] => true
        [/usr/local/bin/pngquant] => true
        [/usr/local/bin/pngcrush] => true
        [pngout] => false
        [/usr/local/bin/advpng] => true
        [/usr/local/bin/gifsicle] => true
        [/usr/local/bin/jpegoptim] => true
        [/usr/local/bin/jpegtran] => true
        [/usr/local/bin/svgo] => true
    )
    
    opened by Flynsarmy 0
  • Make compatible with PSR-12 formatting standard

    Make compatible with PSR-12 formatting standard

    This PR makes your package compatible with PSR-12 coding standards. It also adds a composer phpcs script for ease of use.

    I had to add 3 rule exceptions in .phpcs.xml for stuff you have in your tests. I'd recommend these also be fixed and the exceptions removed.

    i'd also suggest adding composer phpcs to .travis.yml so it's enforced on all future PRs.

    opened by Flynsarmy 0
  • Does not strip creator and quality comments

    Does not strip creator and quality comments

    I noticed that the optimized images still have the CREATOR and QUALITY comments. "CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 75"

    Is there a way these can also be removed?

    opened by Aduffy 0
Owner
Piotr Śliwa
Piotr Śliwa
Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file, move it to a new directory, and returns the new source for the image.

NO LONGER MAINTAINED!!! Image Cache v. 1.0.0 Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file,

Erik Nielsen 455 Dec 30, 2022
A simple page view counter that store data as text and shows data as a PNG image

Image Counter A simple page view counter that store data as text and shows the counter as a PNG image.

Victor Ribeiro 10 Apr 19, 2022
Picasso is a Laravel Image Management and Optimization Package

Picasso is a Laravel Image Management and Optimization Package. Define image dimensions and options, store uploaded image in multiple dimensions with or without a watermark and retrieve optimized images on your website when needed.

Laravelista 82 Nov 24, 2022
GifFrameExtractor is a PHP class that separates all the frames (and their duration) of an animated GIF

================================ GifFrameExtractor ================================ GifFrameExtractor is a PHP class that separates all the frames (an

Clément Guillemain 173 Dec 12, 2022
GifCreator is a PHP class that creates animated GIF from multiple images

================================ GifCreator ================================ GifCreator is a PHP class to create animated GIF from multiple images For

Clément Guillemain 320 Dec 15, 2022
Grabs the dominant color or a representative color palette from an image. Uses PHP and GD, Imagick or Gmagick.

Color Thief PHP A PHP class for grabbing the color palette from an image. Uses PHP and GD or Imagick libraries to make it happen. It's a PHP port of t

Kevin Subileau 610 Dec 28, 2022
Optimize your images on the fly with Glide for Laravel.

Glide for Laravel Optimize your images on the fly with Glide for Laravel. Support us Like our work? You can support us by purchasing one of our produc

Flowframe 53 Oct 17, 2022
Auto Image & file upload, resize and crop for Laravel eloquent model using Intervention image

Laravel ImageUp The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization. Install

QCode.in 708 Dec 22, 2022
A Laravel Gravatar package for retrieving gravatar image URLs or checking the existance of an image.

Gravatar for Laravel 5.x, 6, 7 and 8 Installation First, pull in the package through Composer via the command line: composer require creativeorange/gr

Creativeorange 477 Dec 1, 2022
This plugin adds a new image style for the Core Image block.

This plugin adds a new image style for the Core Image block. Introduction How to use? Go to Gutenberg Editor and add a image block. e.g. Add new image

Mahesh Waghmare 3 Feb 17, 2022
Wonderfully easy on-demand image manipulation library with an HTTP based API.

Glide Glide is a wonderfully easy on-demand image manipulation library written in PHP. Its straightforward API is exposed via HTTP, similar to cloud i

The League of Extraordinary Packages 2.4k Dec 19, 2022
PHPExif is a library which gives you easy access to the EXIF meta-data of an image

PHPExif v0.6.4 PHPExif is a library which gives you easy access to the EXIF meta-data of an image. PHPExif serves as a wrapper around some native or C

null 135 Dec 4, 2022
An easy and elegant way to generate gravatars 🖼

pH2Gravatar The simplest Gravatar PHP package An easy and elegant way to generate gravatar profile photos from email addresses ?? ⛏ Requirements PHP 7

♚ PH⑦ de Soria™♛ 6 Jul 12, 2022
🤹‍♀️Very simple to use Gravatar implementation for Laravel

Very simple to use Gravatar implementation for Laravel. Install, Include the Facade and then generate, simple! Installation You can install the packag

Wavey 11 May 7, 2022
PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

PHP Image Editor PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options ! ✨ Supporting ⭐ Star this repos

Franck Alary 17 Nov 13, 2022
PHP 5.3 Object Oriented image manipulation library

Imagine Tweet about it using the #php_imagine hashtag. Image manipulation library for PHP 5.3 inspired by Python's PIL and other image libraries. Requ

Bulat Shakirzyanov 4.3k Jan 6, 2023
PHP Thumb is a light-weight image manipulation library aimed at thumbnail generation

PHP Thumb NOTICE - This project was recently updated to 2.0 and is PSR-0 compliant and supports Composer integration. Some parts of the documentation

Ian Selby 985 Dec 4, 2022
image sharing site made in PHP just for fun and freetime

2bart image sharing site made in PHP just for fun and freetime To-do list: upload system [DONE] ✔️ views system [DONE] ✔️ image list system [DONE] ✔️

goom 1 Oct 22, 2021
The Gregwar\Image class purpose is to provide a simple object-oriented images handling and caching API

Gregwar's Image class The Gregwar\Image class purpose is to provide a simple object-oriented images handling and caching API. Installation With compos

Grégoire Passault 958 Dec 29, 2022