“Posterize an Image in React: Reduce Color Levels per Channel”
To make an image look like a poster, reduce the R, G, and B values of each pixel to a few levels, which reduces the number of colors used. Read the pixel values with a canvas, then replace each value from 0 to 255 with one of a fixed set, such as 0, 85, 170, or 255 for 4 levels. Smooth gradients then turn into sharp bands of color.
Here I built a function posterize that reduces the colors, and a component App that lets you choose the number of levels, shows the result, and saves it as a PNG. I also tried the same effect with an SVG filter, which is useful when you only need to display the result. For the SVG version, forgetting one attribute shifts the color boundaries. Both points are explained using pixel counts.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. Playwright ran Chromium, selected an image, and I compared the displayed result pixel by pixel with an image produced by the same calculation in Python (Pillow 10.2.0). The image was not a photo but an opaque 600×400 image drawn with Pillow (1,021 colors). I did not test Firefox, Safari, mobile browsers, images with transparent areas, or processing speed on large images such as photos.
- 1. Snap each channel's value to a fixed set of levels
- 2. A component that shows the result for a chosen level count and saves it as PNG
- 3. Compare the displayed result with an image computed in Python
- 4. For display only, the same colors can be made with an SVG filter
- 5. Without color-interpolation-filters, the color boundaries shift
Snap each channel's value to a fixed set of levels
To reduce colors, I apply the same rule to each of R, G, and B. I divide the range 0 to 255 into equal-width intervals, one per level, and map every value in an interval to one fixed value. With 4 levels, 0 to 63 becomes 0, 64 to 127 becomes 85, 128 to 191 becomes 170, and 192 to 255 becomes 255. The output values are the evenly spaced values from 0 to 255.
There are only 256 possible values, so I build a lookup table in advance and just index it for each pixel.
// Build a lookup table that maps values from 0 to 255 down to the given number of levels.
// Split 0 to 255 into levels equal-width ranges, and set the value for the kth range to k * 255 / (levels - 1).
export function makeTable(levels: number): Uint8ClampedArray {
const table = new Uint8ClampedArray(256);
for (let v = 0; v < 256; v++) {
const k = Math.min(levels - 1, Math.floor((v / 255) * levels));
table[v] = Math.round((k * 255) / (levels - 1));
}
return table;
}
// Create an image with R, G, and B each reduced to the given number of levels. Alpha (opacity) is left unchanged.
export function posterize(src: ImageData, levels: number): ImageData {
const table = makeTable(levels);
const out = new ImageData(src.width, src.height);
const a = src.data;
const b = out.data;
for (let i = 0; i < a.length; i += 4) {
b[i] = table[a[i]];
b[i + 1] = table[a[i + 1]];
b[i + 2] = table[a[i + 2]];
b[i + 3] = a[i + 3];
}
return out;
}
// Count the colors used in the image (combinations of R, G, and B).
export function countColors(img: ImageData): number {
const colors = new Set<number>();
const d = img.data;
for (let i = 0; i < d.length; i += 4) {
colors.add((d[i] << 16) | (d[i + 1] << 8) | d[i + 2]);
}
return colors.size;
}
// Load the selected file and get the pixel values.
export async function loadImageData(file: File): Promise<ImageData> {
const bitmap = await createImageBitmap(file);
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('canvas が使えません');
ctx.drawImage(bitmap, 0, 0);
bitmap.close();
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
The data of an ImageData holds four values per pixel, R, G, B, and A, stored in order, row by row from the top-left pixel. So the loop steps four values at a time, replaces only R, G, and B through the table, and copies A unchanged. To get the pixel values, I draw the image loaded with createImageBitmap() onto a canvas that is not shown on the page, then read it with getImageData().
With 4 levels per channel, the maximum number of color combinations is 4×4×4 = 64. The colors actually used are fewer. In the test image, the original 1,021 colors became 20. countColors packs R, G, and B into one number, adds it to a Set, and counts the distinct values.

A component that shows the result for a chosen level count and saves it as PNG
App keeps the original ImageData and the number of levels in state. The reduced image and the color count are computed with useMemo, so they are recalculated only when the image or the level count changes. The result is drawn onto the canvas inside useEffect with putImageData().
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ChangeEvent } from 'react';
import { countColors, loadImageData, posterize } from './posterize';
export function App() {
const [src, setSrc] = useState<ImageData | null>(null);
const [levels, setLevels] = useState(4);
const canvasRef = useRef<HTMLCanvasElement>(null);
// Reduce the colors again only when the image or the number of levels changes.
const result = useMemo(() => (src ? posterize(src, levels) : null), [src, levels]);
const colors = useMemo(() => (result ? countColors(result) : 0), [result]);
// Draw the color-reduced image on the canvas.
useEffect(() => {
const canvas = canvasRef.current;
if (!result || !canvas) return;
canvas.width = result.width;
canvas.height = result.height;
canvas.getContext('2d')?.putImageData(result, 0, 0);
}, [result]);
async function pick(e: ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (file) setSrc(await loadImageData(file));
}
// Save the canvas contents as a PNG.
function save() {
canvasRef.current?.toBlob((blob) => {
if (!blob) return;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `poster-${levels}.png`;
a.click();
URL.revokeObjectURL(url);
}, 'image/png');
}
return (
<main>
<label className="pick">
画像を選ぶ
<input type="file" accept="image/*" onChange={pick} />
</label>
<label className="levels">
1色あたりの段階:{levels}
<input type="range" min={2} max={8} step={1} value={levels} onChange={(e) => setLevels(Number(e.target.value))} />
</label>
{result && (
<>
<p className="info">
使われている色:{colors.toLocaleString()} 色(最大 {(levels ** 3).toLocaleString()} 色)
</p>
<canvas ref={canvasRef} className="result" role="img" aria-label="色の数を減らした画像" />
<button type="button" onClick={save}>
PNG で保存
</button>
</>
)}
</main>
);
}
When the save button is clicked, toBlob() turns the canvas contents into a PNG Blob. A link with a download attribute gets a URL created with URL.createObjectURL(), and the link is clicked to start the download. In the test, clicking save at 4 levels downloaded a file named poster-4.png, and every pixel matched the canvas that was displayed.
The CSS is as follows. The result canvas is kept within the screen width with max-width: 100%. On a 420px-wide screen, the 600×400 result was shown at 389.98×260.66px.
body { margin: 0; font-family: "Noto Sans CJK JP", sans-serif; color: #1f2a30; background: #fff; }
main { padding: 16px; max-width: 620px; }
.pick, .levels { display: flex; align-items: center; gap: 8px; margin: 0 0 10px; font-size: 14px; }
.info { font-size: 14px; margin: 0 0 8px; }
.result { display: block; max-width: 100%; height: auto; border: 1px solid #9aa5ab; margin: 0 0 10px; }
button { font: inherit; font-size: 14px; padding: 6px 14px; }
The following GIF shows the level count changed from 4 to 2 and then from 2 to 8, after an image was selected. The slider moves in steps of 1, so the intermediate levels pass through as well. At 2 levels, each of R, G, and B is either 0 or 255, so the sky became only blue, light blue, and white, and the ground became only black, green, and yellow. At 8 levels the bands become finer, and the result gets closer to the original image.

Compare the displayed result with an image computed in Python
With Playwright, I selected an image and, for each level count, saved the result canvas as a PNG. I compared each saved PNG pixel by pixel with an image computed in Python using the same lookup table.
元の画像の色の数: 1021
段階 4 の対応表の値: [0, 85, 170, 255]
canvas-2.png: 正解と違う画素 0 / 240000, 不透明 True, 色の数 7
canvas-3.png: 正解と違う画素 0 / 240000, 不透明 True, 色の数 13
canvas-4.png: 正解と違う画素 0 / 240000, 不透明 True, 色の数 20
canvas-6.png: 正解と違う画素 0 / 240000, 不透明 True, 色の数 29
canvas-8.png: 正解と違う画素 0 / 240000, 不透明 True, 色の数 40
download-4.png と canvas-4.png: 違う画素 0, 差の最大 0
At every level count, the number of pixels that differed from the Python result was 0. The color counts shown on the page (7, 13, 20, 29, 40) also matched the counts from Python.
For display only, the same colors can be made with an SVG filter
If you do not need to save the image and only need to display it, you can reduce the colors with an SVG filter instead of a canvas. Setting type="discrete" on <feFuncR>, <feFuncG>, and <feFuncB> inside <feComponentTransfer> replaces values band by band. In the specification's formula for discrete, the input range 0 to 1 is divided into as many intervals as there are values in tableValues, and the k-th interval is replaced by the k-th value. This is the same division as in makeTable.
import { useId } from 'react';
type Props = { src: string; levels: number; alt: string; linear?: boolean };
// In an SVG filter, reduce the color levels only when displaying (pixel values are not extracted).
export function SvgPosterize({ src, levels, alt, linear = false }: Props) {
const id = useId();
// If the number of levels is 4, then "0 0.3333333333333333 0.6666666666666666 1"
const table = Array.from({ length: levels }, (_, k) => String(k / (levels - 1))).join(' ');
return (
<>
<svg width="0" height="0" style={{ position: 'absolute' }} aria-hidden="true">
<filter id={id} colorInterpolationFilters={linear ? 'linearRGB' : 'sRGB'}>
<feComponentTransfer>
<feFuncR type="discrete" tableValues={table} />
<feFuncG type="discrete" tableValues={table} />
<feFuncB type="discrete" tableValues={table} />
</feComponentTransfer>
</filter>
</svg>
<img src={src} alt={alt} style={{ filter: `url(#${id})` }} />
</>
);
}
The filter id is created with useId, and the filter is applied to <img> with url() in the CSS filter property. Several instances of this component on the same page do not collide. In the test, the filter value looked like url("#_r_0_"), and the filter was applied.
I took a 1:1 screenshot of the image displayed with this component and compared it with the result computed on a canvas.
svg-4-srgb.png: (600, 400) canvas の結果(正解)と違う画素 0 / 240000, 差の最大 0, 色の数 20
svg-2-srgb.png: (600, 400) canvas の結果(正解)と違う画素 0 / 240000, 差の最大 0, 色の数 7
svg-8-srgb.png: (600, 400) canvas の結果(正解)と違う画素 186778 / 240000, 差の最大 1, 色の数 40
At 2 and 4 levels, every pixel matched the canvas result. At 8 levels, the color count was the same (40), but some pixels differed from the canvas result by 1. Looking at the values in the gray band, the positions where the value changes were the same as in the canvas, but the interval that is 73, 146, and 219 in the canvas came out as 72, 145, and 218 in the SVG filter.
canvas-8 の灰色の帯(x と値): 0:0 74:36 150:73 225:109 300:146 375:182 450:219 526:255
svg-8-srgb の灰色の帯(x と値): 0:0 74:36 150:72 225:109 300:145 375:182 450:218 526:255
The values written in tableValues also affect the result. When I rounded the 4-level values to four decimal places and wrote 0 0.3333 0.6667 1, the interval that is 85 in the canvas became 84. For that reason, the component converts k / (levels - 1) to a string without rounding.
svg-4-srgb-4digits の灰色の帯(x と値): 0:0 150:84 300:170 450:255
An SVG filter only changes how the image looks on screen. If you want to save the reduced image as a file, use the canvas approach.
Without color-interpolation-filters, the color boundaries shift
The <filter> specifies color-interpolation-filters="sRGB" because the default value of this attribute is linearRGB. <feComponentTransfer> also handles values in the linearRGB color space unless specified otherwise. With 4 levels and linearRGB left as is, the image was completely different from the canvas result.
svg-4-linear.png: (600, 400) canvas の結果(正解)と違う画素 231120 / 240000, 差の最大 170, 色の数 17

The difference is clear in the gray band. In the canvas result, the 600px-wide band is split into four 150px sections. With linearRGB, the black section extends 321px from the left edge, and the following values are 156, 213, and 255. The darker side collapses into black.
canvas-4 の灰色の帯(x と値): 0:0 150:85 300:170 450:255
svg-4-linear の灰色の帯(x と値): 0:0 321:156 441:213 528:255
To divide the R, G, and B values of the image file evenly, as they are stored, specify color-interpolation-filters="sRGB". In React JSX, write it as colorInterpolationFilters.





