1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace tkanstantsin\fileupload\formatter\adapter; |
5
|
|
|
|
6
|
|
|
use Imagine\Image\Palette\RGB as RGBPalette; |
7
|
|
|
use Imagine\Image\Point; |
8
|
|
|
use Imagine\Imagick\Imagine; |
9
|
|
|
use tkanstantsin\fileupload\config\InvalidConfigException; |
10
|
|
|
use tkanstantsin\fileupload\model\BaseObject; |
11
|
|
|
use tkanstantsin\fileupload\model\IFile; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class BackgroundFixer replaces transparent background in PNG image that |
15
|
|
|
* would be converted in JPG |
16
|
|
|
*/ |
17
|
|
|
class BackgroundFixer extends BaseObject implements IFormatAdapter |
18
|
|
|
{ |
19
|
|
|
public const DEFAULT_EXTENSION = 'jpg'; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Used for jpg images which may be png originally and have transparency. |
23
|
|
|
* @var string |
24
|
|
|
*/ |
25
|
|
|
public $transparentBackground = 'ffffff'; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @inheritdoc |
29
|
|
|
* @throws \tkanstantsin\fileupload\config\InvalidConfigException |
30
|
|
|
*/ |
31
|
|
|
public function init(): void |
32
|
|
|
{ |
33
|
|
|
parent::init(); |
34
|
|
|
|
35
|
|
|
if ($this->transparentBackground === null) { |
36
|
|
|
throw new InvalidConfigException('Background color not defined'); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Applies filters or something to content and return it |
42
|
|
|
* |
43
|
|
|
* @param IFile $file |
44
|
|
|
* @param $content |
45
|
|
|
* |
46
|
|
|
* @return mixed |
47
|
|
|
* @throws \UnexpectedValueException |
48
|
|
|
* @throws \Imagine\Exception\InvalidArgumentException |
49
|
|
|
* @throws \Imagine\Exception\RuntimeException |
50
|
|
|
* @throws \ImageOptimizer\Exception\Exception |
51
|
|
|
*/ |
52
|
|
|
public function exec(IFile $file, $content) |
53
|
|
|
{ |
54
|
|
|
$imagine = new Imagine(); |
55
|
|
|
$image = $imagine->load($content); |
56
|
|
|
|
57
|
|
|
if (!\in_array(mb_strtolower($file->getExtension() ?? self::DEFAULT_EXTENSION), ['jpg', 'jpeg'], true)) { |
58
|
|
|
return $image; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$palette = new RGBPalette(); |
62
|
|
|
$backgroundColor = $palette->color($this->transparentBackground, 100); |
63
|
|
|
$background = $imagine->create($image->getSize(), $backgroundColor); |
64
|
|
|
|
65
|
|
|
return $background->paste($image, new Point(0, 0)); |
66
|
|
|
} |
67
|
|
|
} |