Skip to content

Commit 688ae9b

Browse files
author
Jakub Caban
committed
Implement LimitColors
1 parent ad2f591 commit 688ae9b

File tree

2 files changed

+71
-5
lines changed

2 files changed

+71
-5
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ $manager = new ImageManager(['driver' => 'vips']);
4646
- [x] InsertCommand
4747
- [x] InterlaceCommand
4848
- [x] InvertCommand
49+
- [x] LimitColorsCommand
4950
- [x] MaskCommand
5051
- [x] OpacityCommand
5152
- [x] PickColorCommand
@@ -58,7 +59,6 @@ $manager = new ImageManager(['driver' => 'vips']);
5859
- [x] SharpenCommand
5960
- [x] TrimCommand
6061
- [x] WidenCommand
61-
- [ ] LimitColorsCommand
6262

6363
### Shapes
6464

src/Commands/LimitColorsCommand.php

Lines changed: 70 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,85 @@
44

55
namespace Intervention\Image\Vips\Commands;
66

7-
use Intervention\Image\Exception\NotSupportedException;
7+
use Intervention\Image\Vips\Color;
8+
use Jcupitt\Vips\BlendMode;
9+
use Jcupitt\Vips\Image;
810

911
class LimitColorsCommand extends AbstractCommand
1012
{
1113
/**
1214
* Execute the command.
1315
*
1416
* @param \Intervention\Image\Image $image
15-
* @return void
16-
* @throws \Intervention\Image\Exception\NotSupportedException
17+
* @return bool
1718
*/
1819
public function execute($image)
1920
{
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+
);
2187
}
2288
}

0 commit comments

Comments
 (0)