/
MozJpegPostProcessor.php
107 lines (90 loc) · 2.85 KB
/
MozJpegPostProcessor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/*
* This file is part of the `liip/LiipImagineBundle` project.
*
* (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace Liip\ImagineBundle\Imagine\Filter\PostProcessor;
use Liip\ImagineBundle\Binary\BinaryInterface;
use Liip\ImagineBundle\Model\Binary;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
/**
* mozjpeg post-processor, for noticably better jpeg compression.
*
* @see http://calendar.perfplanet.com/2014/mozjpeg-3-0/
* @see https://mozjpeg.codelove.de/binaries.html
*
* @author Alex Wilson <a@ax.gy>
*/
class MozJpegPostProcessor implements PostProcessorInterface
{
/**
* @var string Path to the mozjpeg cjpeg binary
*/
protected $mozjpegBin;
/**
* @var null|int Quality factor
*/
protected $quality;
/**
* Constructor.
*
* @param string $mozjpegBin Path to the mozjpeg cjpeg binary
* @param int|null $quality Quality factor
*/
public function __construct(
$mozjpegBin = '/opt/mozjpeg/bin/cjpeg',
$quality = null
) {
$this->mozjpegBin = $mozjpegBin;
$this->setQuality($quality);
}
/**
* @param int $quality
*
* @return MozJpegPostProcessor
*/
public function setQuality($quality)
{
$this->quality = $quality;
return $this;
}
/**
* @param BinaryInterface $binary
* @param array $options
*
* @throws ProcessFailedException
*
* @return BinaryInterface
*/
public function process(BinaryInterface $binary, array $options = []): BinaryInterface
{
$type = mb_strtolower($binary->getMimeType());
if (!in_array($type, ['image/jpeg', 'image/jpg'], true)) {
return $binary;
}
$processArguments = [$this->mozjpegBin];
// Places emphasis on DC
$processArguments[] = '-quant-table';
$processArguments[] = 2;
$transformQuality = array_key_exists('quality', $options) ? $options['quality'] : $this->quality;
if (null !== $transformQuality) {
$processArguments[] = '-quality';
$processArguments[] = $transformQuality;
}
$processArguments[] = '-optimise';
// Favor stdin/stdout so we don't waste time creating a new file.
$proc = new Process($processArguments);
$proc->setInput($binary->getContent());
$proc->run();
if (false !== mb_strpos($proc->getOutput(), 'ERROR') || 0 !== $proc->getExitCode()) {
throw new ProcessFailedException($proc);
}
$result = new Binary($proc->getOutput(), $binary->getMimeType(), $binary->getFormat());
return $result;
}
}