Palette from Image — PHP source
Extract the dominant colors from any image as a reusable palette — median-cut quantization with population shares, hex and rgb, copyable — runs entirely in your browser.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* palette-from-image — dominant colors from RGBA pixels via median-cut quantization.
*
* Language: PHP 7.4+ (standard library only).
* CosmoDev polyglot showcase port of the `palette-from-image` tool, ported from
* src/lib/palette-extract.ts (the canonical TypeScript implementation).
*
* usort was not stable until PHP 8.0, and the TS lib's determinism depends
* on stable sorts — so rows are decorated with their original index before
* sorting. Averages round via floor(x + 0.5) to mirror Math.round (PHP's
* round() breaks ties away from zero).
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
/** Stable sort by numeric key: decorating with the index keeps ties in input
* order even on PHP 7.4, where usort is not yet stable. */
function stable_sort_by_key(array $rows, callable $key): array
{
$decorated = [];
foreach ($rows as $i => $row) {
$decorated[] = [$key($row), $i, $row];
}
usort($decorated, static fn (array $a, array $b): int => ($a[0] <=> $b[0]) ?: ($a[1] <=> $b[1]));
return array_map(static fn (array $d) => $d[2], $decorated);
}
/** Math.round as the ECMAScript spec defines it: floor(x + 0.5). */
function ts_round(float $x): int
{
return (int) floor($x + 0.5);
}
/** Per-channel [min, max] pairs reduced over a bucket of [r, g, b] pixels. */
function channel_extremes(array $bucket): array
{
$cols = [array_column($bucket, 0), array_column($bucket, 1), array_column($bucket, 2)];
return [
[min($cols[0]), min($cols[1]), min($cols[2])],
[max($cols[0]), max($cols[1]), max($cols[2])],
];
}
/** Split a bucket in two at the median of its widest channel (ties: r, g, b). */
function split_bucket(array $bucket): array
{
[$lo, $hi] = channel_extremes($bucket);
$ranges = [$hi[0] - $lo[0], $hi[1] - $lo[1], $hi[2] - $lo[2]];
// First max wins ties — r, then g, then b, exactly like the TS reduce.
$channel = $ranges[2] > $ranges[$ranges[1] > $ranges[0] ? 1 : 0]
? 2
: ($ranges[1] > $ranges[0] ? 1 : 0);
$sorted = stable_sort_by_key($bucket, static fn (array $p): int => $p[$channel]);
$mid = intdiv(count($sorted), 2);
return [array_slice($sorted, 0, $mid), array_slice($sorted, $mid)];
}
/**
* Extract up to $maxColors dominant swatches from a flat RGBA byte array —
* 4 bytes per pixel, e.g. array_values(unpack('C*', $imageBytes)) from GD.
* Empty or fully-transparent input yields an empty palette.
*
* @return array<int, array{r: int, g: int, b: int, population: int}>
*/
function extract_palette(array $rgba, int $maxColors = 8): array
{
$total = intdiv(count($rgba), 4);
if ($total === 0) {
return [];
}
$stride = max(1, intdiv($total, 16384));
$pixels = [];
for ($i = 0; $i < $total; $i += $stride) {
$o = $i * 4;
if ($rgba[$o + 3] === 0) {
continue; // fully transparent — skip
}
$pixels[] = [$rgba[$o], $rgba[$o + 1], $rgba[$o + 2]];
}
if ($pixels === []) {
return [];
}
// Median-cut: split until $maxColors buckets or all buckets are uniform.
$buckets = [$pixels];
while (count($buckets) < $maxColors) {
// Widest-range bucket with more than one distinct value wins the split.
$bestIdx = -1;
$bestRange = 1; // range 1 (exact duplicates only) never splits further
foreach ($buckets as $i => $bucket) {
[$lo, $hi] = channel_extremes($bucket);
$range = max($hi[0] - $lo[0], $hi[1] - $lo[1], $hi[2] - $lo[2]);
if ($range > $bestRange) {
$bestRange = $range;
$bestIdx = $i;
}
}
if ($bestIdx === -1) {
break; // every bucket is uniform — done
}
[$lo, $hi] = split_bucket(array_splice($buckets, $bestIdx, 1)[0]);
$buckets[] = $lo;
$buckets[] = $hi;
}
$swatches = [];
foreach ($buckets as $bucket) {
if ($bucket === []) {
continue;
}
$n = count($bucket);
$swatches[] = [
'r' => ts_round(array_sum(array_column($bucket, 0)) / $n),
'g' => ts_round(array_sum(array_column($bucket, 1)) / $n),
'b' => ts_round(array_sum(array_column($bucket, 2)) / $n),
'population' => $n,
];
}
// Descending population; stable, so ties keep bucket order — matches TS.
return stable_sort_by_key($swatches, static fn (array $s): int => -$s['population']);
}
/** Format a swatch as #rrggbb. */
function to_hex(array $swatch): string
{
return sprintf('#%02x%02x%02x', $swatch['r'], $swatch['g'], $swatch['b']);
}
// Usage: extract_palette(unpack('C*', $rgbaBytes), 6), then to_hex($swatch).
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →