Skip to content

Novis\Image\Image::palette

Returns the main colours of an image, the most common colour first.

Image::palette reads an encoded image and returns an array of Color values. You can pass bytes, an open Core\IO\File or an uploaded Core\Request\Part. You choose how many colours you want with count, which is 5 by default. The array can be shorter than count when the image has fewer colours. Transparent pixels are not counted.

A count above 256 throws a LogicError. Bytes that are not an image throw a ParseError.

Good to know: use the first colour as the background of a card or a page header, so the page matches the photo. Each Color has the numbers r, g, b and alpha. You use them to write the colour in CSS.

The examples below show the colours of a photo with two colours, a page header in the main colour, and the error for a count that is too large.

Parameters

  • $dataCore\Bytes::Source
  • $countuintdefault 5

Return value

Returns array<Color>.

Examples

Two colours

<?nvs
// Shows the colours `Image::palette` finds in an image with two colours.
use Novis\Image\Color;
use Novis\Image\Image;
// A blue image of 60 by 60 pixels with an orange square of 20 by 20 pixels on it.
Image $square = Image::create(20, 20, Color::hex('#f97316'));
tainted bytes $photo = Image::create(60, 60, Color::hex('#2563eb'))->withOverlay($square, { x: 20, y: 20 })->encode();
// Blue covers more pixels, so it comes first.
foreach (Image::palette($photo, 2) as Color $colour) {
echo $colour->r, ' ', $colour->g, ' ', $colour->b, "\n";
}
Output
37 99 235
249 115 22

Header in the main colour

<?nvs
// Shows how a blog colours the header of a post with the main colour of its photo.
use Novis\Image\Color;
use Novis\Image\Image;
tainted bytes $photo = Image::create(120, 80, Color::hex('#16a34a'))->encode();
// `count: 1` returns only the most common colour.
Color $main = Image::palette($photo, 1)[0];
// This prints a CSS rule with that colour.
echo ".post-header { background: rgb({$main->r} {$main->g} {$main->b}); }\n";
Output
.post-header { background: rgb(22 163 74); }

Count too large

<?nvs
// Shows the error `Image::palette` throws for a `count` above 256.
use Novis\Image\Color;
use Novis\Image\Image;
tainted bytes $photo = Image::create(16, 16, Color::hex('#2563eb'))->encode();
// 1000 colours is more than 256, so this throws a `LogicError`.
try {
echo Core\Arr::count(Image::palette($photo, 1000)), "\n";
} catch (LogicError $e) {
echo 'LogicError: ', $e->message, "\n";
}
Output
LogicError: a palette has at most 256 colours, and 1000 were asked for