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