1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|
// GIF89a encoder: median-cut quantization (≤256 colors), optional Floyd–Steinberg
// dithering, single transparent index when the image has transparent pixels.
/** Median-cut palette from RGBA data, refined with a few k-means passes. Returns [[r,g,b], ...]. */
export function medianCutPalette(data, maxColors = 256) {
// 15-bit histogram, also accumulating the true channel sums so averages stay exact.
const hist = new Uint32Array(32768);
const sums = new Float64Array(32768 * 3);
const n = data.length / 4;
const stride = Math.max(1, Math.floor(n / 250000));
for (let p = 0; p < n; p += stride) {
const i = p * 4;
if (data[i + 3] < 128) continue;
const k = ((data[i] >> 3) << 10) | ((data[i + 1] >> 3) << 5) | (data[i + 2] >> 3);
hist[k]++;
sums[k * 3] += data[i];
sums[k * 3 + 1] += data[i + 1];
sums[k * 3 + 2] += data[i + 2];
}
const bins = [];
for (let k = 0; k < 32768; k++) if (hist[k]) bins.push(k);
if (!bins.length) return [[0, 0, 0]];
const mean = (k, c) => sums[k * 3 + c] / hist[k];
if (bins.length <= maxColors) return bins.map((k) => [0, 1, 2].map((c) => Math.round(mean(k, c))));
const makeBox = (list) => {
const min = [255, 255, 255], max = [0, 0, 0];
let count = 0;
for (const k of list) {
for (let c = 0; c < 3; c++) {
const v = mean(k, c);
if (v < min[c]) min[c] = v;
if (v > max[c]) max[c] = v;
}
count += hist[k];
}
return { list, min, max, count };
};
const boxes = [makeBox(bins)];
while (boxes.length < maxColors) {
// split the box with the largest (range * population)
let best = -1, bestScore = 0;
for (let i = 0; i < boxes.length; i++) {
const b = boxes[i];
if (b.list.length < 2) continue;
const range = Math.max(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]);
const score = range * Math.sqrt(b.count);
if (score > bestScore) { bestScore = score; best = i; }
}
if (best < 0) break;
const b = boxes[best];
const ranges = [0, 1, 2].map((c) => b.max[c] - b.min[c]);
const c = ranges.indexOf(Math.max(...ranges));
b.list.sort((x, y) => mean(x, c) - mean(y, c));
let acc = 0, cut = 0;
for (; cut < b.list.length - 1; cut++) {
acc += hist[b.list[cut]];
if (acc >= b.count / 2) break;
}
const left = b.list.slice(0, cut + 1), right = b.list.slice(cut + 1);
if (!right.length) break;
boxes.splice(best, 1, makeBox(left), makeBox(right));
}
let palette = boxes.map((b) => {
let r = 0, g = 0, bl = 0;
for (const k of b.list) { r += sums[k * 3]; g += sums[k * 3 + 1]; bl += sums[k * 3 + 2]; }
return [r / b.count, g / b.count, bl / b.count];
});
// k-means refinement over the histogram bins
for (let iter = 0; iter < 4; iter++) {
const acc = palette.map(() => [0, 0, 0, 0]);
for (const k of bins) {
const r = mean(k, 0), g = mean(k, 1), b = mean(k, 2);
let bi = 0, bd = Infinity;
for (let i = 0; i < palette.length; i++) {
const p = palette[i];
const d = (p[0] - r) ** 2 * 2 + (p[1] - g) ** 2 * 4 + (p[2] - b) ** 2 * 3;
if (d < bd) { bd = d; bi = i; }
}
const a = acc[bi];
a[0] += sums[k * 3]; a[1] += sums[k * 3 + 1]; a[2] += sums[k * 3 + 2]; a[3] += hist[k];
}
palette = palette.map((p, i) => (acc[i][3] ? [acc[i][0] / acc[i][3], acc[i][1] / acc[i][3], acc[i][2] / acc[i][3]] : p));
}
return palette.map((p) => p.map((v) => Math.round(v)));
}
/** Map pixels to palette indices. transparentIndex used for alpha < 128. */
export function mapToPalette(imageData, palette, { dither = true, transparentIndex = -1, offset = 0 } = {}) {
const { width: w, height: h, data } = imageData;
const out = new Uint8Array(w * h);
const cache = new Int16Array(32768).fill(-1);
const nearest = (r, g, b) => {
const key = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
let idx = cache[key];
if (idx >= 0) return idx;
let best = 0, bestD = Infinity;
for (let i = 0; i < palette.length; i++) {
const p = palette[i];
const dr = p[0] - r, dg = p[1] - g, db = p[2] - b;
const d = dr * dr * 2 + dg * dg * 4 + db * db * 3;
if (d < bestD) { bestD = d; best = i; }
}
cache[key] = best;
return best;
};
const err = dither ? new Float32Array(w * h * 3) : null;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const p = y * w + x;
const i = p * 4;
if (data[i + 3] < 128 && transparentIndex >= 0) { out[p] = transparentIndex; continue; }
let r = data[i], g = data[i + 1], b = data[i + 2];
if (err) {
r = Math.max(0, Math.min(255, r + err[p * 3]));
g = Math.max(0, Math.min(255, g + err[p * 3 + 1]));
b = Math.max(0, Math.min(255, b + err[p * 3 + 2]));
}
const idx = nearest(r | 0, g | 0, b | 0);
out[p] = idx + offset;
if (err) {
const c = palette[idx];
const er = r - c[0], eg = g - c[1], eb = b - c[2];
const spread = (q, k) => { err[q * 3] += er * k; err[q * 3 + 1] += eg * k; err[q * 3 + 2] += eb * k; };
if (x + 1 < w) spread(p + 1, 7 / 16);
if (y + 1 < h) {
if (x > 0) spread(p + w - 1, 3 / 16);
spread(p + w, 5 / 16);
if (x + 1 < w) spread(p + w + 1, 1 / 16);
}
}
}
}
return out;
}
function lzwEncode(indices, minCodeSize) {
const bytes = [];
let cur = 0, curBits = 0;
const emit = (code, size) => {
cur |= code << curBits;
curBits += size;
while (curBits >= 8) {
bytes.push(cur & 0xff);
cur >>>= 8;
curBits -= 8;
}
};
const clear = 1 << minCodeSize, eoi = clear + 1;
let codeSize = minCodeSize + 1;
let next = eoi + 1;
let table = new Map();
emit(clear, codeSize);
let prefix = indices[0];
for (let i = 1; i < indices.length; i++) {
const k = indices[i];
const key = (prefix << 8) | k;
const found = table.get(key);
if (found !== undefined) { prefix = found; continue; }
emit(prefix, codeSize);
if (next === 4096) {
emit(clear, codeSize);
next = eoi + 1;
codeSize = minCodeSize + 1;
table = new Map();
} else {
if (next >= (1 << codeSize)) codeSize++;
table.set(key, next++);
}
prefix = k;
}
emit(prefix, codeSize);
emit(eoi, codeSize);
if (curBits > 0) bytes.push(cur & 0xff);
return bytes;
}
export function encodeGIF(imageData, { dither = true, colors = 256 } = {}) {
const { width: w, height: h, data } = imageData;
let hasAlpha = false;
for (let i = 3; i < data.length; i += 4) if (data[i] < 128) { hasAlpha = true; break; }
const maxColors = Math.max(2, Math.min(256, colors) - (hasAlpha ? 1 : 0));
const palette = medianCutPalette(data, maxColors);
const offset = hasAlpha ? 1 : 0; // index 0 = transparent
const indices = mapToPalette(imageData, palette, { dither, transparentIndex: hasAlpha ? 0 : -1, offset });
const total = palette.length + offset;
let tableBits = 1;
while ((1 << tableBits) < total) tableBits++;
const tableSize = 1 << tableBits;
const minCodeSize = Math.max(2, tableBits);
const out = [];
const u16 = (v) => out.push(v & 0xff, (v >> 8) & 0xff);
for (const c of 'GIF89a') out.push(c.charCodeAt(0));
u16(w); u16(h);
out.push(0x80 | 0x70 | (tableBits - 1), 0, 0);
for (let i = 0; i < tableSize; i++) {
const c = i < offset ? [0, 0, 0] : palette[i - offset] || [0, 0, 0];
out.push(c[0], c[1], c[2]);
}
if (hasAlpha) out.push(0x21, 0xf9, 0x04, 0x01, 0, 0, 0, 0x00);
out.push(0x2c);
u16(0); u16(0); u16(w); u16(h);
out.push(0);
out.push(minCodeSize);
const lzw = lzwEncode(indices, minCodeSize);
for (let i = 0; i < lzw.length; i += 255) {
const chunk = lzw.slice(i, i + 255);
out.push(chunk.length, ...chunk);
}
out.push(0, 0x3b);
return new Blob([new Uint8Array(out)], { type: 'image/gif' });
}
|