Skip to content

Commit

Permalink
Fix dithering process
Browse files Browse the repository at this point in the history
  • Loading branch information
zk-phi committed Jul 3, 2024
1 parent fdb5a1d commit 31a7dc0
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/utils/binarize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
Expand All @@ -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;
}
}
}
Expand Down

0 comments on commit 31a7dc0

Please sign in to comment.