To reduce the color depth of an image (e.g., converting a 24-bit PNG to an 8-bit indexed format), you must first load the image data into a PointContainer, build a color palette from that container, and then apply the palette back to the container.
Note: This example uses pngjs for file reading, but image-q can work with various sources via PointContainer methods.
import { PNG } from 'pngjs';
import { buildPaletteSync, utils, applyPaletteSync } from 'image-q';
import fs from 'fs';
// 1. Read file and convert to PointContainer
const { data, width, height } = PNG.sync.read(fs.readFileSync('file.png'));
const inPointContainer = utils.PointContainer.fromUint8Array(
data,
width,
height,
);
// 2. Build the palette from the image
const palette = buildPaletteSync([inPointContainer]);
// 3. Apply the palette to create the indexed image
const outPointContainer = applyPaletteSync(inPointContainer, palette);
// Use outPointContainer.toUint8Array() to get the resulting data