ForHosting KIT · Images

Quantize a color to the nearest palette entry

#42A5F5 checked against #000, #369, #ffffff and #3fa7f2 snaps to #3fa7f2 at position 3, with a squared distance of 22. Keep picked colors inside the set your brand, device or file format allows. Free in your browser.

  • Free
  • Runs in your browser
  • No sign-up
  • Your data stays on your device
Use it from WebAPIEmailTelegramApp soon
If you enter
Color
#42A5F5
Palette
#000, #369, #ffffff, #3fa7f2
You get
Color
#42a5f5
Quantized color
#3fa7f2
Palette index
3
Distance squared
22

Quantize a color to a fixed palette when an indexed image, terminal theme, LED controller, design token set, or constrained export format can use only approved colors. Provide one hexadecimal source color and an ordered palette. The capability validates every value, compares exact RGB distances, and returns the nearest normalized palette color, its zero-based index, and the squared distance. Equal matches always select the earliest palette entry, so repeated runs produce identical output.

Prepare a deliberate fixed palette

Color quantization begins with the colors the destination is actually allowed to store or display. Put those colors in the palette array in a stable, intentional order, using #RGB or #RRGGBB notation. Short forms are expanded before comparison, and letter case does not affect the result.

The source color follows the same notation. A palette can contain between one and 256 entries, which covers small brand sets, terminal colors, classic indexed-image tables, embroidery thread selections, and many device-specific color maps. Palette order matters only when two entries are equally distant from the source.

In that case, the earlier entry wins. This explicit rule makes ties predictable and also lets you express preference without changing the colors themselves. Keep the palette fixed across a batch when you need consistent indexed output.

If different jobs silently use reordered palettes, the returned index may change even when the selected color value does not. The validator rejects empty arrays, oversized arrays, missing hash prefixes, unsupported alpha channels, malformed digits, and non-string entries instead of guessing what was intended.

Understand the deterministic distance calculation

Each accepted color is expanded to six hexadecimal digits and decoded into red, green, and blue channel values from 0 through 255. The algorithm subtracts each palette channel from the corresponding source channel, squares the three differences, and adds them. The palette entry with the smallest total is selected.

The comparison uses a strict less-than update, so an equal distance never replaces an earlier candidate. That detail establishes deterministic tie handling even for symmetric palettes or duplicate entries.

Create indexed image data

Map sampled pixels to positions in a fixed color table before writing an indexed representation.

Enforce brand colors

Snap an arbitrary picked color to the closest member of an approved design-system palette.

Target limited hardware

Choose the nearest supported RGB value for LEDs, displays, terminals, or other devices with constrained colors.

Which color formats are accepted?

The source and every palette entry must use #RGB or #RRGGBB hexadecimal notation. Alpha channels and unprefixed values are rejected.

How is the nearest color selected?

The algorithm minimizes the sum of squared red, green, and blue channel differences in encoded RGB space.

What happens when two palette colors are equally near?

The entry appearing first in the palette wins, making the result deterministic.

Is the returned palette index zero-based?

Yes. The first palette entry has index 0, the second has index 1, and so on.

Is this a perceptual color match?

No. It uses direct RGB Euclidean distance for simple, exact, reproducible indexed output rather than a perceptual color model.

Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.

POSThttps://api.kit.forhosting.com/color/quantize-to-palette

Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.

curl -X POST https://api.kit.forhosting.com/color/quantize-to-palette \
  -H "Authorization: Bearer $KIT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"color":"#42a5f5","palette":["#000000","#336699","#ffffff"]}'
{
  "color": "#42a5f5",
  "palette": [
    "#000000",
    "#336699",
    "#ffffff"
  ]
}
{
  "task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
  "type": "color.quantize_to_palette",
  "status": "queued",
  "_links": {
    "result": "/tasks/tsk_…/result"
  }
}

The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.

Per request$0.002

Published price — no tokens, no invented credits. A failed task is never charged.

max_items256
HTTPCodeMeaning
401unauthorizedMissing or invalid API key.
402insufficient_balanceYour balance doesn't cover the task price.
404unknown_typeThat task type doesn't exist.
429rate_limitedToo many requests. Use the webhook instead of polling.

Understand the deterministic distance calculation

The returned distance_squared value is this exact integer total; no square root is needed because taking a square root cannot change which nonnegative distance is smallest. This is ordinary Euclidean distance in encoded RGB space, chosen for transparent and reproducible indexed conversion rather than perceptual color science. It is fast, has no environmental dependencies, and produces the same answer in the browser and API. The result also includes the normalized source color and zero-based palette_index, allowing a caller to write an index directly while retaining the selected hexadecimal color for logs, previews, or downstream validation.

Use the result safely in an indexed workflow

Indexes start at zero, matching common array and image-processing conventions. A value of zero means the source was already present in the palette, while a larger value indicates more channel movement. Your application can establish a domain-specific maximum and reject conversions that move too far, although this capability always returns the mathematically nearest valid entry rather than imposing an arbitrary quality threshold. Process multiple source colors by calling the same pure operation for each item with the same ordered palette. For a single lookup, use quantized_color anywhere the destination expects the chosen hexadecimal value. For indexed storage, use palette_index as the stable position in the exact palette supplied with the request. Preserve the palette alongside stored indexes; an index has no independent color meaning after the palette is reordered or replaced. distance_squared is useful for quality controls. There is no network access, random choice, date, hidden state, or adaptive model, so identical input produces identical JSON.

What does an API request cost?

Each API request costs $0.002. The browser version runs the same deterministic logic locally.

Read the full KIT documentation →