|
| 1 | +import { JimpClass } from "@jimp/types"; |
| 2 | +import { applyPaletteSync, buildPaletteSync, utils } from "image-q"; |
| 3 | +import z from "zod"; |
| 4 | + |
| 5 | +const QuantizeOptionsSchema = z.object({ |
| 6 | + colors: z.number().optional(), |
| 7 | + colorDistanceFormula: z |
| 8 | + .union([ |
| 9 | + z.literal("cie94-textiles"), |
| 10 | + z.literal("cie94-graphic-arts"), |
| 11 | + z.literal("ciede2000"), |
| 12 | + z.literal("color-metric"), |
| 13 | + z.literal("euclidean"), |
| 14 | + z.literal("euclidean-bt709-noalpha"), |
| 15 | + z.literal("euclidean-bt709"), |
| 16 | + z.literal("manhattan"), |
| 17 | + z.literal("manhattan-bt709"), |
| 18 | + z.literal("manhattan-nommyde"), |
| 19 | + z.literal("pngquant"), |
| 20 | + ]) |
| 21 | + .optional(), |
| 22 | + paletteQuantization: z |
| 23 | + .union([ |
| 24 | + z.literal("neuquant"), |
| 25 | + z.literal("neuquant-float"), |
| 26 | + z.literal("rgbquant"), |
| 27 | + z.literal("wuquant"), |
| 28 | + ]) |
| 29 | + .optional(), |
| 30 | + imageQuantization: z |
| 31 | + .union([ |
| 32 | + z.literal("nearest"), |
| 33 | + z.literal("riemersma"), |
| 34 | + z.literal("floyd-steinberg"), |
| 35 | + z.literal("false-floyd-steinberg"), |
| 36 | + z.literal("stucki"), |
| 37 | + z.literal("atkinson"), |
| 38 | + z.literal("jarvis"), |
| 39 | + z.literal("burkes"), |
| 40 | + z.literal("sierra"), |
| 41 | + z.literal("two-sierra"), |
| 42 | + z.literal("sierra-lite"), |
| 43 | + ]) |
| 44 | + .optional(), |
| 45 | +}); |
| 46 | + |
| 47 | +export type QuantizeOptions = z.infer<typeof QuantizeOptionsSchema>; |
| 48 | + |
| 49 | +export const methods = { |
| 50 | + /** |
| 51 | + * Image color number reduction. |
| 52 | + */ |
| 53 | + quantize<I extends JimpClass>( |
| 54 | + image: I, |
| 55 | + { |
| 56 | + colors, |
| 57 | + colorDistanceFormula, |
| 58 | + paletteQuantization, |
| 59 | + imageQuantization, |
| 60 | + }: QuantizeOptions |
| 61 | + ) { |
| 62 | + const inPointContainer = utils.PointContainer.fromUint8Array( |
| 63 | + image.bitmap.data, |
| 64 | + image.bitmap.width, |
| 65 | + image.bitmap.height |
| 66 | + ); |
| 67 | + |
| 68 | + const palette = buildPaletteSync([inPointContainer], { |
| 69 | + colors, |
| 70 | + colorDistanceFormula, |
| 71 | + paletteQuantization, |
| 72 | + }); |
| 73 | + const outPointContainer = applyPaletteSync(inPointContainer, palette, { |
| 74 | + colorDistanceFormula, |
| 75 | + imageQuantization, |
| 76 | + }); |
| 77 | + |
| 78 | + image.bitmap.data = Buffer.from(outPointContainer.toUint8Array()); |
| 79 | + |
| 80 | + return image; |
| 81 | + }, |
| 82 | +}; |
0 commit comments