UICraft / Craft
CanvasImage to Bitmap

How Image to Bitmap works

Turn an uploaded image into a grid of colored dots with threshold, halftone, ordered, and error diffusion modes.

Demo
Image / bitmapChoose an image
Render mode

How it works

01 — Start with an image and a canvas

An image supplies the colors. A <canvas> is a rectangle of pixels that JavaScript can draw into. Start with the source and an empty result side by side:

<img src="/image-bitmap-sample.svg" alt="Mountain illustration" />
<canvas role="img" aria-label="Bitmap version of the mountain illustration" />

The finished component draws the result on the canvas. Its src prop loads the sample above, and a file input or drop lets you replace it. You never read pixels directly from an <img> element: first you draw the decoded image onto a canvas.

02 — Load the file before reading it

An uploaded File contains encoded image bytes, such as PNG or JPEG bytes. URL.createObjectURL gives that file a temporary local URL. new Image() asks the browser to decode it; onload runs once the browser knows its natural dimensions and can draw it.

const url = URL.createObjectURL(file);
const image = new Image();
image.onload = () => setImg(image);
image.onerror = () => setError("Could not load image.");
image.src = url;

The component accepts image files, revokes the temporary URL when it replaces the image or unmounts, and ignores older loads if a newer file wins the race. For a URL supplied through src, it requests CORS access. A remote server must allow that access before getImageData can read its pixels.

03 — Draw a small copy and get its pixels

A column is one dot across; a row is one dot down. The original image may be thousands of pixels wide, but we only need one sampled color for each dot. naturalWidth and naturalHeight are the decoded image dimensions in pixels. This formula keeps their ratio when choosing the number of rows:

const rows = Math.max(1, Math.round((cols * img.naturalHeight) / img.naturalWidth));
const off = document.createElement("canvas");
off.width = cols;
off.height = rows;
const octx = off.getContext("2d", { willReadFrequently: true });
if (!octx) return;
 
octx.fillStyle = "#000";
octx.fillRect(0, 0, cols, rows);
octx.drawImage(img, 0, 0, cols, rows);
const data = octx.getImageData(0, 0, cols, rows).data;

drawImage scales the whole source into the small offscreen canvas. The browser combines source pixels as it scales, leaving cols × rows samples. The black fill gives transparent parts a predictable dark background. getImageData(left, top, width, height) then copies that canvas rectangle into memory. The component catches an error here because a cross-origin image without CORS permission makes the canvas unreadable.

04 — Find one cell in the image data

data is a flat Uint8ClampedArray: four numbers per pixel in red, green, blue, alpha order. Each channel ranges from 0 to 255; alpha is opacity. Pixels run left to right, then top to bottom. For cell (x, y), skip y complete rows, move x pixels across, then multiply by four channels:

const i = (y * cols + x) * 4;
const red = data[i];
const green = data[i + 1];
const blue = data[i + 2];
const alpha = data[i + 3];

For example, in a 64-column grid, cell (2, 1) starts at (1 × 64 + 2) × 4 = 264. Its red value is data[264], green is data[265], blue is data[266], and alpha is data[267]. The renderer uses the RGB values for Original color; it does not need alpha because the black background was painted first.

05 — Turn each sample into brightness

Luminance estimates how bright a color looks. Green contributes more than blue to this estimate. The Threshold slider shifts brightness before the modes use it; Invert flips light and dark:

const i = (y * cols + x) * 4;
let brightness = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
if (invert) brightness = 255 - brightness;
brightness = Math.max(0, Math.min(255, brightness + 128 - threshold));

Try moving Threshold in Binary mode. A dot switches on when its adjusted brightness exceeds 128. The component stores all cell brightness values in a Float32Array so the other modes can use them too.

06 — Choose the dots and draw them

Halftone makes brighter cells into larger circles. Binary uses one cutoff. Bayer compares each cell with a repeating 4 × 4 threshold pattern. Dither sends the difference between the chosen black or white value and the cell brightness to neighboring cells; this is error diffusion.

// Halftone: circle area grows with brightness.
const radius = Math.sqrt(brightness / 255) * CELL * 0.5;
 
// Binary: a cell is either lit or dark.
const lit = brightness > 128;

Try the four modes on the sample sky. The visible canvas is cols * CELL pixels wide; ctx.arc draws each dot and ctx.fill paints it. A React effect redraws when the image or a control changes. The canvas stays inside a fixed-height preview, so changing the column count resizes the image without moving the controls. toBlob creates the downloadable PNG.

07 — Clean up and make the controls accessible

An object URL keeps the uploaded file available to the browser. Revoke the old URL after a replacement loads, and revoke the current one when the component unmounts:

if (urlRef.current) URL.revokeObjectURL(urlRef.current);
urlRef.current = isObjectUrl ? url : null;
 
useEffect(() => () => {
  if (urlRef.current) URL.revokeObjectURL(urlRef.current);
}, []);

The finished component also ignores stale image loads. Mode buttons expose their selection with aria-pressed, the canvas has an image label, and errors use role="alert". The upload and controls work from the keyboard as well as with drag and drop.

Check: In a 64-column grid, what array index holds the blue channel for cell (2, 1)? What happens to the number of sampled cells if you double the columns while keeping the same image ratio?