From 31a7dc075e3c6afd27836cf2c8edc3949464d792 Mon Sep 17 00:00:00 2001 From: zk-phi Date: Wed, 3 Jul 2024 16:52:52 +0900 Subject: [PATCH] Fix dithering process --- src/utils/binarize.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/utils/binarize.ts b/src/utils/binarize.ts index e0a991e6..5f00e2ac 100644 --- a/src/utils/binarize.ts +++ b/src/utils/binarize.ts @@ -3,14 +3,14 @@ // This reduces number of colors before quantization, and also // offers better result by dithering quantization errors. -const THRESHOLD = 80; +const THRESHOLD = 128; export const binarizeTransparency = ( data: Uint8ClampedArray, width: number, height: number, ): void => { - const err: number[] = new Array(width * height); + const err: number[] = (new Array(width * height)).fill(0); for (let y = 0; y < height; y += 1) { if (y % 2 === 0) { // iterate from left to right for (let x = 0; x < width; x += 1) { @@ -30,11 +30,11 @@ export const binarizeTransparency = ( } /* eslint-enable no-param-reassign */ // Floyd-steinberg dithering - if (x + 1 < width) err[y * width + (x + 1)] = newErr * 7 / 16; + if (x + 1 < width) err[y * width + (x + 1)] += newErr * 7 / 16; if (y + 1 < height) { - if (x - 1 >= 0) err[(y + 1) * width + (x - 1)] = newErr * 3 / 16; - err[(y + 1) * width + x] = newErr * 5 / 16; - if (x + 1 < width) err[(y + 1) * width + (x + 1)] = newErr * 1 / 16; + if (x - 1 >= 0) err[(y + 1) * width + (x - 1)] += newErr * 3 / 16; + err[(y + 1) * width + x] += newErr * 5 / 16; + if (x + 1 < width) err[(y + 1) * width + (x + 1)] += newErr * 1 / 16; } } } else { // iterate from right to left @@ -55,11 +55,11 @@ export const binarizeTransparency = ( } /* eslint-enable no-param-reassign */ // Floyd-steinberg dithering - if (x - 1 >= 0) err[y * width + (x - 1)] = newErr * 7 / 16; + if (x - 1 >= 0) err[y * width + (x - 1)] += newErr * 7 / 16; if (y + 1 < height) { - if (x + 1 < width) err[(y + 1) * width + (x + 1)] = newErr * 3 / 16; - err[(y + 1) * width + x] = newErr * 5 / 16; - if (x - 1 >= 0) err[(y + 1) * width + (x - 1)] = newErr * 1 / 16; + if (x + 1 < width) err[(y + 1) * width + (x + 1)] += newErr * 3 / 16; + err[(y + 1) * width + x] += newErr * 5 / 16; + if (x - 1 >= 0) err[(y + 1) * width + (x - 1)] += newErr * 1 / 16; } } }