Skip to content

Commit

Permalink
Merge branch 'master' of github.com:spatie/image
Browse files Browse the repository at this point in the history
  • Loading branch information
freekmurze committed Jul 2, 2017
2 parents 77437c6 + f83f9b9 commit c4961b8
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
"require": {
"php": "^7.0",
"league/glide": "^1.2",
"spatie/temporary-directory": "^1.0.0"
"ps/image-optimizer": "^1.1",
"spatie/temporary-directory": "^1.0.0",
"symfony/process": "^3.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0",
Expand Down
32 changes: 31 additions & 1 deletion src/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Spatie\Image;

use BadMethodCallException;
use ImageOptimizer\OptimizerFactory;
use Spatie\Image\Exceptions\InvalidImageDriver;

/** @mixin \Spatie\Image\Manipulations */
Expand All @@ -14,9 +15,11 @@ class Image
/** @var \Spatie\Image\Manipulations */
protected $manipulations;

/** @var */
protected $imageDriver = 'gd';

protected $shouldOptimize = false;
protected $optimizationOptions = [];

/**
* @param string $pathToImage
*
Expand Down Expand Up @@ -86,6 +89,20 @@ public function getManipulationSequence(): ManipulationSequence
return $this->manipulations->getManipulationSequence();
}

/**
* @param array $optimizationOptions
*
* @return $this
*/
public function optimize($optimizationOptions = [])
{
$this->optimizationOptions = $optimizationOptions;

$this->shouldOptimize = true;

return $this;
}

public function save($outputPath = '')
{
if ($outputPath == '') {
Expand All @@ -98,6 +115,19 @@ public function save($outputPath = '')
->useImageDriver($this->imageDriver)
->performManipulations($this->manipulations)
->save($outputPath);

if ($this->shouldOptimize) {
$this->performOptimization($outputPath);
}
}

protected function performOptimization($path)
{
$factory = new OptimizerFactory($this->optimizationOptions);

$optimizer = $factory->get();

$optimizer->optimize($path);
}

protected function addFormatManipulation($outputPath)
Expand Down
12 changes: 12 additions & 0 deletions tests/ImageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ public function it_will_not_force_the_format_according_to_the_output_extension_w
$this->assertImageType($targetFile, IMAGETYPE_JPEG);
}

/** @test */
public function it_can_optimize_an_image()
{
$targetFile = $this->tempDir->path('optimized.jpg');

Image::load($this->getTestFile('test.jpg'))
->optimize()
->save($targetFile);

$this->assertFileExists($targetFile);
}

protected function assertImageType(string $filePath, $expectedType)
{
$expectedType = image_type_to_mime_type($expectedType);
Expand Down

0 comments on commit c4961b8

Please sign in to comment.