Palette from Image — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! palette-from-image — dominant colors from RGBA pixels via median-cut quantization.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `palette-from-image` tool, ported
//! from src/lib/palette-extract.ts (the canonical TypeScript implementation).
//!
//! `slice::sort_by` is a stable merge sort, so the TS lib's deterministic
//! stable sorts carry over unchanged; rounding goes through floor(x + 0.5)
//! to mirror Math.round (f64::round breaks ties away from zero). Input is
//! flat RGBA bytes — the layout of canvas ImageData.data.
//!
//! display source — part of CosmoDev's polyglot tool pages.
/// One dominant color: averaged RGB plus the pixel count it represents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Swatch {
pub r: u8,
pub g: u8,
pub b: u8,
pub population: usize,
}
/// A single opaque pixel, unpacked from the flat RGBA byte stream.
type Pixel = (u8, u8, u8);
/// Down-sample so large images quantize in bounded time (TS: MAX_SAMPLES).
const MAX_SAMPLES: usize = 16_384;
/// Extract up to `max_colors` dominant swatches (the tool's UI passes 8) from
/// flat RGBA bytes. Empty or fully-transparent input yields an empty palette.
pub fn extract_palette(rgba: &[u8], max_colors: usize) -> Vec<Swatch> {
let total = rgba.len() / 4;
if total == 0 {
return Vec::new();
}
let stride = (total / MAX_SAMPLES).max(1);
let pixels: Vec<Pixel> = (0..total)
.step_by(stride)
.filter(|&i| rgba[i * 4 + 3] != 0) // skip fully transparent pixels
.map(|i| (rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]))
.collect();
if pixels.is_empty() {
return Vec::new();
}
// Median-cut: split until max_colors buckets or all buckets are uniform.
let mut buckets: Vec<Vec<Pixel>> = vec![pixels];
while buckets.len() < max_colors {
// Widest-range bucket with more than one distinct value wins the split.
let mut best_idx = None;
let mut best_range = 1u16; // range 1 (exact duplicates) never splits
for (i, bucket) in buckets.iter().enumerate() {
let ranges = channel_ranges(bucket);
let range = ranges[0].max(ranges[1]).max(ranges[2]);
if range > best_range {
best_range = range;
best_idx = Some(i);
}
}
let Some(idx) = best_idx else { break }; // every bucket is uniform — done
let (lo, hi) = split_bucket(&buckets.remove(idx));
buckets.push(lo);
buckets.push(hi);
}
let mut swatches: Vec<Swatch> = buckets
.iter()
.filter(|b| !b.is_empty())
.map(|b| Swatch {
r: ts_round(b.iter().map(|&(r, _, _)| r as u64).sum(), b.len()),
g: ts_round(b.iter().map(|&(_, g, _)| g as u64).sum(), b.len()),
b: ts_round(b.iter().map(|&(_, _, b)| b as u64).sum(), b.len()),
population: b.len(),
})
.collect();
// sort_by is stable, so population ties keep bucket order — matches TS.
swatches.sort_by(|a, b| b.population.cmp(&a.population));
swatches
}
/// Math.round as the ECMAScript spec defines it: floor(x + 0.5).
fn ts_round(sum: u64, n: usize) -> u8 {
((sum as f64 / n as f64) + 0.5).floor() as u8
}
/// Per-channel (r, g, b) min→max ranges reduced over a bucket.
fn channel_ranges(bucket: &[Pixel]) -> [u16; 3] {
let (mut lo, mut hi) = ([255u8; 3], [0u8; 3]);
for &(r, g, b) in bucket {
let px = [r, g, b];
for c in 0..3 {
lo[c] = lo[c].min(px[c]);
hi[c] = hi[c].max(px[c]);
}
}
[(hi[0] - lo[0]).into(), (hi[1] - lo[1]).into(), (hi[2] - lo[2]).into()]
}
/// Split a bucket in two at the median of its widest channel (ties: r, g, b).
fn split_bucket(bucket: &[Pixel]) -> (Vec<Pixel>, Vec<Pixel>) {
let ranges = channel_ranges(bucket);
// First max wins ties — r, then g, then b, exactly like the TS reduce.
let mut channel = 0usize;
for c in 1..3 {
if ranges[c] > ranges[channel] {
channel = c;
}
}
let mut sorted = bucket.to_vec();
sorted.sort_by_key(|&(r, g, b)| [r, g, b][channel]); // stable sort
let mid = sorted.len() / 2;
let hi = sorted.split_off(mid);
(sorted, hi)
}
/// Format a swatch as #rrggbb.
pub fn to_hex(s: &Swatch) -> String {
format!("#{:02x}{:02x}{:02x}", s.r, s.g, s.b)
}
// Usage: extract_palette(&rgba_bytes, 6), then to_hex(&swatch) per 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 →