|
4 | 4 |
|
5 | 5 | namespace Intervention\Image\Vips\Commands; |
6 | 6 |
|
7 | | -use Intervention\Image\Exception\NotSupportedException; |
| 7 | +use Intervention\Image\Vips\Color; |
| 8 | +use Jcupitt\Vips\BlendMode; |
| 9 | +use Jcupitt\Vips\Image; |
8 | 10 |
|
9 | 11 | class LimitColorsCommand extends AbstractCommand |
10 | 12 | { |
11 | 13 | /** |
12 | 14 | * Execute the command. |
13 | 15 | * |
14 | 16 | * @param \Intervention\Image\Image $image |
15 | | - * @return void |
16 | | - * @throws \Intervention\Image\Exception\NotSupportedException |
| 17 | + * @return bool |
17 | 18 | */ |
18 | 19 | public function execute($image) |
19 | 20 | { |
20 | | - throw new NotSupportedException('LimitColors command is not supported by VIPS driver.'); |
| 21 | + $count = $this->argument(0)->type('int')->value(); |
| 22 | + $matte = $this->argument(1)->value(); |
| 23 | + |
| 24 | + $bits = 8; |
| 25 | + if ($count < 3) { |
| 26 | + $bits = 1; |
| 27 | + } elseif ($count < 5) { |
| 28 | + $bits = 2; |
| 29 | + } elseif ($count < 17) { |
| 30 | + $bits = 4; |
| 31 | + } |
| 32 | + |
| 33 | + return $this->handleCommand( |
| 34 | + function () use ($image, $bits, $matte) { |
| 35 | + /** @var Image $core */ |
| 36 | + $core = $image->getCore(); |
| 37 | + |
| 38 | + $alpha = null; |
| 39 | + if($core->hasAlpha()) { |
| 40 | + $alpha = $this->extractAlphaChannel($core); |
| 41 | + $core = $this->flattenImage($core); |
| 42 | + } |
| 43 | + |
| 44 | + if($matte) { |
| 45 | + $matteColor = new Color($matte); |
| 46 | + |
| 47 | + $canvas = $image->getDriver()->newImage( |
| 48 | + $core->width, |
| 49 | + $core->height, |
| 50 | + $matteColor->getRgba() |
| 51 | + ); |
| 52 | + |
| 53 | + $buffer = $core->pngsave_buffer( |
| 54 | + [ |
| 55 | + 'palette' => true, |
| 56 | + 'bitdepth' => $bits, |
| 57 | + 'dither' => 0.5, |
| 58 | + 'Q' => 90, |
| 59 | + ] |
| 60 | + ); |
| 61 | + $core = Image::pngload_buffer($buffer); |
| 62 | + if($alpha) { |
| 63 | + $core = $core->bandjoin($alpha); |
| 64 | + } |
| 65 | + |
| 66 | + $canvas = $canvas->getCore()->composite2($core, BlendMode::OVER); |
| 67 | + |
| 68 | + $image->setCore($canvas); |
| 69 | + } else { |
| 70 | + $buffer = $core->pngsave_buffer( |
| 71 | + [ |
| 72 | + 'palette' => true, |
| 73 | + 'bitdepth' => $bits, |
| 74 | + 'dither' => 0.5, |
| 75 | + 'Q' => 90, |
| 76 | + ] |
| 77 | + ); |
| 78 | + $core = Image::pngload_buffer($buffer); |
| 79 | + if ($alpha) { |
| 80 | + $core = $core->bandjoin($alpha); |
| 81 | + } |
| 82 | + |
| 83 | + $image->setCore($core); |
| 84 | + } |
| 85 | + } |
| 86 | + ); |
21 | 87 | } |
22 | 88 | } |
0 commit comments