k-centroid-scaler 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,138 @@
1
+ # K-Centroid Image Scaler - WebAssembly Module
2
+
3
+ A Rust/WebAssembly implementation of the K-Centroid image downscaling algorithm, converted from the original Lua/Aseprite script.
4
+
5
+ ## Algorithm Overview
6
+
7
+ The K-Centroid scaler uses K-means clustering to intelligently downscale images:
8
+
9
+ 1. **Tile Division**: The image is divided into tiles based on the target dimensions
10
+ 2. **K-Means Clustering**: Each tile undergoes K-means clustering to identify dominant colors
11
+ 3. **Color Selection**: The most dominant color (centroid with most pixels) represents each tile
12
+ 4. **Downscaling**: Each pixel in the output image uses the dominant color from its corresponding tile
13
+
14
+ This approach preserves important color information better than simple averaging, making it ideal for pixel art and images where color fidelity is important.
15
+
16
+ ## Module Interface
17
+
18
+ ### Main Function
19
+
20
+ ```rust
21
+ k_centroid_resize(
22
+ image_data: &[u8], // RGBA image buffer
23
+ original_width: u32, // Source image width
24
+ original_height: u32, // Source image height
25
+ target_width: u32, // Desired output width
26
+ target_height: u32, // Desired output height
27
+ centroids: u32, // Number of color centroids (2-16 recommended)
28
+ iterations: u32, // K-means iterations (1-20 recommended)
29
+ ) -> ImageResult
30
+ ```
31
+
32
+ ### Return Value
33
+
34
+ ```javascript
35
+ {
36
+ data: Uint8Array, // RGBA pixel data
37
+ width: number, // Output width
38
+ height: number // Output height
39
+ }
40
+ ```
41
+
42
+ ## Build Instructions
43
+
44
+ ### Prerequisites
45
+
46
+ - Rust toolchain (`curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh`)
47
+ - wasm-pack (`curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh`)
48
+
49
+ ### Building
50
+
51
+ ```bash
52
+ # Make the build script executable
53
+ chmod +x build.sh
54
+
55
+ # Run the build script
56
+ ./build.sh
57
+
58
+ # Or manually:
59
+ wasm-pack build --target web --out-dir pkg
60
+ ```
61
+
62
+ ## Usage Example
63
+
64
+ ```javascript
65
+ import init, { process_image } from './pkg/k_centroid_scaler.js';
66
+
67
+ async function downscaleImage() {
68
+ // Initialize the WASM module
69
+ await init();
70
+
71
+ // Get your image data (e.g., from a canvas)
72
+ const canvas = document.getElementById('myCanvas');
73
+ const ctx = canvas.getContext('2d');
74
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
75
+
76
+ // Process the image
77
+ const result = process_image(
78
+ imageData.data,
79
+ canvas.width,
80
+ canvas.height,
81
+ Math.floor(canvas.width / 2), // Half size
82
+ Math.floor(canvas.height / 2),
83
+ 4, // 4 centroids per tile
84
+ 5 // 5 iterations
85
+ );
86
+
87
+ // Use the result
88
+ const outputImageData = new ImageData(
89
+ new Uint8ClampedArray(result.data),
90
+ result.width,
91
+ result.height
92
+ );
93
+
94
+ // Draw to output canvas
95
+ const outputCanvas = document.getElementById('output');
96
+ const outputCtx = outputCanvas.getContext('2d');
97
+ outputCanvas.width = result.width;
98
+ outputCanvas.height = result.height;
99
+ outputCtx.putImageData(outputImageData, 0, 0);
100
+ }
101
+ ```
102
+
103
+ ## Parameters Guide
104
+
105
+ ### `centroids` (2-16)
106
+ - **Lower values (2-4)**: Stronger color quantization, more stylized results
107
+ - **Higher values (8-16)**: Better color preservation, closer to original
108
+
109
+ ### `iterations` (1-20)
110
+ - **Lower values (1-3)**: Faster processing, less accurate clustering
111
+ - **Higher values (10-20)**: More accurate color selection, slower processing
112
+
113
+ ## Behavior Notes
114
+
115
+ 1. **Deterministic Results**: Uses a fixed random seed (1) for consistent K-means initialization
116
+ 2. **Dominant Color Selection**: Always selects the centroid with the most assigned pixels
117
+ 3. **Tile Processing**: Each tile is processed independently, maintaining local color characteristics
118
+ 4. **Edge Handling**: Properly handles edge tiles that may be smaller than the standard tile size
119
+
120
+ ## Performance Considerations
121
+
122
+ - **Complexity**: O(n × k × i) where n = pixels per tile, k = centroids, i = iterations
123
+ - **Memory**: Lightweight, processes tiles individually
124
+ - **WebAssembly Optimizations**:
125
+ - Compiled with size optimizations (`opt-level = "z"`)
126
+ - Link-time optimization enabled
127
+ - Optional wasm-opt post-processing
128
+
129
+ ## Differences from Original Lua Version
130
+
131
+ 1. **Output**: Returns only the downscaled image (not the intermediate K-tiles visualization)
132
+ 2. **Language**: Rust provides better performance and type safety
133
+ 3. **Platform**: Runs in browsers via WebAssembly instead of Aseprite
134
+ 4. **Interface**: Direct buffer manipulation instead of Aseprite API calls
135
+
136
+ ## License
137
+
138
+ Converted to Rust/WebAssembly for web usage. Original algorithm from Aseprite Lua script.
@@ -0,0 +1,466 @@
1
+ let wasm;
2
+
3
+ let heap = new Array(128).fill(undefined);
4
+
5
+ heap.push(undefined, null, true, false);
6
+
7
+ function getObject(idx) { return heap[idx]; }
8
+
9
+ let heap_next = heap.length;
10
+
11
+ function addHeapObject(obj) {
12
+ if (heap_next === heap.length) heap.push(heap.length + 1);
13
+ const idx = heap_next;
14
+ heap_next = heap[idx];
15
+
16
+ heap[idx] = obj;
17
+ return idx;
18
+ }
19
+
20
+ let cachedUint8ArrayMemory0 = null;
21
+
22
+ function getUint8ArrayMemory0() {
23
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
24
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
25
+ }
26
+ return cachedUint8ArrayMemory0;
27
+ }
28
+
29
+ function getArrayU8FromWasm0(ptr, len) {
30
+ ptr = ptr >>> 0;
31
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
32
+ }
33
+
34
+ function handleError(f, args) {
35
+ try {
36
+ return f.apply(this, args);
37
+ } catch (e) {
38
+ wasm.__wbindgen_export_0(addHeapObject(e));
39
+ }
40
+ }
41
+
42
+ function debugString(val) {
43
+ // primitive types
44
+ const type = typeof val;
45
+ if (type == 'number' || type == 'boolean' || val == null) {
46
+ return `${val}`;
47
+ }
48
+ if (type == 'string') {
49
+ return `"${val}"`;
50
+ }
51
+ if (type == 'symbol') {
52
+ const description = val.description;
53
+ if (description == null) {
54
+ return 'Symbol';
55
+ } else {
56
+ return `Symbol(${description})`;
57
+ }
58
+ }
59
+ if (type == 'function') {
60
+ const name = val.name;
61
+ if (typeof name == 'string' && name.length > 0) {
62
+ return `Function(${name})`;
63
+ } else {
64
+ return 'Function';
65
+ }
66
+ }
67
+ // objects
68
+ if (Array.isArray(val)) {
69
+ const length = val.length;
70
+ let debug = '[';
71
+ if (length > 0) {
72
+ debug += debugString(val[0]);
73
+ }
74
+ for(let i = 1; i < length; i++) {
75
+ debug += ', ' + debugString(val[i]);
76
+ }
77
+ debug += ']';
78
+ return debug;
79
+ }
80
+ // Test for built-in
81
+ const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
82
+ let className;
83
+ if (builtInMatches && builtInMatches.length > 1) {
84
+ className = builtInMatches[1];
85
+ } else {
86
+ // Failed to match the standard '[object ClassName]'
87
+ return toString.call(val);
88
+ }
89
+ if (className == 'Object') {
90
+ // we're a user defined class or Object
91
+ // JSON.stringify avoids problems with cycles, and is generally much
92
+ // easier than looping through ownProperties of `val`.
93
+ try {
94
+ return 'Object(' + JSON.stringify(val) + ')';
95
+ } catch (_) {
96
+ return 'Object';
97
+ }
98
+ }
99
+ // errors
100
+ if (val instanceof Error) {
101
+ return `${val.name}: ${val.message}\n${val.stack}`;
102
+ }
103
+ // TODO we could test for more things here, like `Set`s and `Map`s.
104
+ return className;
105
+ }
106
+
107
+ let WASM_VECTOR_LEN = 0;
108
+
109
+ const cachedTextEncoder = new TextEncoder();
110
+
111
+ if (!('encodeInto' in cachedTextEncoder)) {
112
+ cachedTextEncoder.encodeInto = function (arg, view) {
113
+ const buf = cachedTextEncoder.encode(arg);
114
+ view.set(buf);
115
+ return {
116
+ read: arg.length,
117
+ written: buf.length
118
+ };
119
+ }
120
+ }
121
+
122
+ function passStringToWasm0(arg, malloc, realloc) {
123
+
124
+ if (realloc === undefined) {
125
+ const buf = cachedTextEncoder.encode(arg);
126
+ const ptr = malloc(buf.length, 1) >>> 0;
127
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
128
+ WASM_VECTOR_LEN = buf.length;
129
+ return ptr;
130
+ }
131
+
132
+ let len = arg.length;
133
+ let ptr = malloc(len, 1) >>> 0;
134
+
135
+ const mem = getUint8ArrayMemory0();
136
+
137
+ let offset = 0;
138
+
139
+ for (; offset < len; offset++) {
140
+ const code = arg.charCodeAt(offset);
141
+ if (code > 0x7F) break;
142
+ mem[ptr + offset] = code;
143
+ }
144
+
145
+ if (offset !== len) {
146
+ if (offset !== 0) {
147
+ arg = arg.slice(offset);
148
+ }
149
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
150
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
151
+ const ret = cachedTextEncoder.encodeInto(arg, view);
152
+
153
+ offset += ret.written;
154
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
155
+ }
156
+
157
+ WASM_VECTOR_LEN = offset;
158
+ return ptr;
159
+ }
160
+
161
+ let cachedDataViewMemory0 = null;
162
+
163
+ function getDataViewMemory0() {
164
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
165
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
166
+ }
167
+ return cachedDataViewMemory0;
168
+ }
169
+
170
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
171
+
172
+ cachedTextDecoder.decode();
173
+
174
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
175
+ let numBytesDecoded = 0;
176
+ function decodeText(ptr, len) {
177
+ numBytesDecoded += len;
178
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
179
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
180
+ cachedTextDecoder.decode();
181
+ numBytesDecoded = len;
182
+ }
183
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
184
+ }
185
+
186
+ function getStringFromWasm0(ptr, len) {
187
+ ptr = ptr >>> 0;
188
+ return decodeText(ptr, len);
189
+ }
190
+
191
+ function dropObject(idx) {
192
+ if (idx < 132) return;
193
+ heap[idx] = heap_next;
194
+ heap_next = idx;
195
+ }
196
+
197
+ function takeObject(idx) {
198
+ const ret = getObject(idx);
199
+ dropObject(idx);
200
+ return ret;
201
+ }
202
+
203
+ function passArray8ToWasm0(arg, malloc) {
204
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
205
+ getUint8ArrayMemory0().set(arg, ptr / 1);
206
+ WASM_VECTOR_LEN = arg.length;
207
+ return ptr;
208
+ }
209
+ /**
210
+ * @param {Uint8Array} image_data
211
+ * @param {number} original_width
212
+ * @param {number} original_height
213
+ * @param {number} target_width
214
+ * @param {number} target_height
215
+ * @param {number} centroids
216
+ * @param {number} iterations
217
+ * @returns {ImageResult}
218
+ */
219
+ export function k_centroid_resize(image_data, original_width, original_height, target_width, target_height, centroids, iterations) {
220
+ const ptr0 = passArray8ToWasm0(image_data, wasm.__wbindgen_export_1);
221
+ const len0 = WASM_VECTOR_LEN;
222
+ const ret = wasm.k_centroid_resize(ptr0, len0, original_width, original_height, target_width, target_height, centroids, iterations);
223
+ return ImageResult.__wrap(ret);
224
+ }
225
+
226
+ /**
227
+ * @param {Uint8Array} data
228
+ * @param {number} width
229
+ * @param {number} height
230
+ * @param {number} target_width
231
+ * @param {number} target_height
232
+ * @param {number} centroids
233
+ * @param {number} iterations
234
+ * @returns {any}
235
+ */
236
+ export function process_image(data, width, height, target_width, target_height, centroids, iterations) {
237
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_export_1);
238
+ const len0 = WASM_VECTOR_LEN;
239
+ const ret = wasm.process_image(ptr0, len0, width, height, target_width, target_height, centroids, iterations);
240
+ return takeObject(ret);
241
+ }
242
+
243
+ const ImageResultFinalization = (typeof FinalizationRegistry === 'undefined')
244
+ ? { register: () => {}, unregister: () => {} }
245
+ : new FinalizationRegistry(ptr => wasm.__wbg_imageresult_free(ptr >>> 0, 1));
246
+
247
+ export class ImageResult {
248
+
249
+ static __wrap(ptr) {
250
+ ptr = ptr >>> 0;
251
+ const obj = Object.create(ImageResult.prototype);
252
+ obj.__wbg_ptr = ptr;
253
+ ImageResultFinalization.register(obj, obj.__wbg_ptr, obj);
254
+ return obj;
255
+ }
256
+
257
+ __destroy_into_raw() {
258
+ const ptr = this.__wbg_ptr;
259
+ this.__wbg_ptr = 0;
260
+ ImageResultFinalization.unregister(this);
261
+ return ptr;
262
+ }
263
+
264
+ free() {
265
+ const ptr = this.__destroy_into_raw();
266
+ wasm.__wbg_imageresult_free(ptr, 0);
267
+ }
268
+ /**
269
+ * @returns {number}
270
+ */
271
+ get width() {
272
+ const ret = wasm.__wbg_get_imageresult_width(this.__wbg_ptr);
273
+ return ret >>> 0;
274
+ }
275
+ /**
276
+ * @param {number} arg0
277
+ */
278
+ set width(arg0) {
279
+ wasm.__wbg_set_imageresult_width(this.__wbg_ptr, arg0);
280
+ }
281
+ /**
282
+ * @returns {number}
283
+ */
284
+ get height() {
285
+ const ret = wasm.__wbg_get_imageresult_height(this.__wbg_ptr);
286
+ return ret >>> 0;
287
+ }
288
+ /**
289
+ * @param {number} arg0
290
+ */
291
+ set height(arg0) {
292
+ wasm.__wbg_set_imageresult_height(this.__wbg_ptr, arg0);
293
+ }
294
+ /**
295
+ * @returns {Uint8Array}
296
+ */
297
+ get data() {
298
+ try {
299
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
300
+ wasm.imageresult_data(retptr, this.__wbg_ptr);
301
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
302
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
303
+ var v1 = getArrayU8FromWasm0(r0, r1).slice();
304
+ wasm.__wbindgen_export_3(r0, r1 * 1, 1);
305
+ return v1;
306
+ } finally {
307
+ wasm.__wbindgen_add_to_stack_pointer(16);
308
+ }
309
+ }
310
+ }
311
+ if (Symbol.dispose) ImageResult.prototype[Symbol.dispose] = ImageResult.prototype.free;
312
+
313
+ const EXPECTED_RESPONSE_TYPES = new Set(['basic', 'cors', 'default']);
314
+
315
+ async function __wbg_load(module, imports) {
316
+ if (typeof Response === 'function' && module instanceof Response) {
317
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
318
+ try {
319
+ return await WebAssembly.instantiateStreaming(module, imports);
320
+
321
+ } catch (e) {
322
+ const validResponse = module.ok && EXPECTED_RESPONSE_TYPES.has(module.type);
323
+
324
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
325
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
326
+
327
+ } else {
328
+ throw e;
329
+ }
330
+ }
331
+ }
332
+
333
+ const bytes = await module.arrayBuffer();
334
+ return await WebAssembly.instantiate(bytes, imports);
335
+
336
+ } else {
337
+ const instance = await WebAssembly.instantiate(module, imports);
338
+
339
+ if (instance instanceof WebAssembly.Instance) {
340
+ return { instance, module };
341
+
342
+ } else {
343
+ return instance;
344
+ }
345
+ }
346
+ }
347
+
348
+ function __wbg_get_imports() {
349
+ const imports = {};
350
+ imports.wbg = {};
351
+ imports.wbg.__wbg_length_6bb7e81f9d7713e4 = function(arg0) {
352
+ const ret = getObject(arg0).length;
353
+ return ret;
354
+ };
355
+ imports.wbg.__wbg_new_19c25a3f2fa63a02 = function() {
356
+ const ret = new Object();
357
+ return addHeapObject(ret);
358
+ };
359
+ imports.wbg.__wbg_newwithlength_a167dcc7aaa3ba77 = function(arg0) {
360
+ const ret = new Uint8Array(arg0 >>> 0);
361
+ return addHeapObject(ret);
362
+ };
363
+ imports.wbg.__wbg_set_1353b2a5e96bc48c = function(arg0, arg1, arg2) {
364
+ getObject(arg0).set(getArrayU8FromWasm0(arg1, arg2));
365
+ };
366
+ imports.wbg.__wbg_set_453345bcda80b89a = function() { return handleError(function (arg0, arg1, arg2) {
367
+ const ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2));
368
+ return ret;
369
+ }, arguments) };
370
+ imports.wbg.__wbg_wbindgendebugstring_99ef257a3ddda34d = function(arg0, arg1) {
371
+ const ret = debugString(getObject(arg1));
372
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export_1, wasm.__wbindgen_export_2);
373
+ const len1 = WASM_VECTOR_LEN;
374
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
375
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
376
+ };
377
+ imports.wbg.__wbg_wbindgenthrow_451ec1a8469d7eb6 = function(arg0, arg1) {
378
+ throw new Error(getStringFromWasm0(arg0, arg1));
379
+ };
380
+ imports.wbg.__wbindgen_cast_2241b6af4c4b2941 = function(arg0, arg1) {
381
+ // Cast intrinsic for `Ref(String) -> Externref`.
382
+ const ret = getStringFromWasm0(arg0, arg1);
383
+ return addHeapObject(ret);
384
+ };
385
+ imports.wbg.__wbindgen_cast_d6cd19b81560fd6e = function(arg0) {
386
+ // Cast intrinsic for `F64 -> Externref`.
387
+ const ret = arg0;
388
+ return addHeapObject(ret);
389
+ };
390
+ imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
391
+ takeObject(arg0);
392
+ };
393
+
394
+ return imports;
395
+ }
396
+
397
+ function __wbg_init_memory(imports, memory) {
398
+
399
+ }
400
+
401
+ function __wbg_finalize_init(instance, module) {
402
+ wasm = instance.exports;
403
+ __wbg_init.__wbindgen_wasm_module = module;
404
+ cachedDataViewMemory0 = null;
405
+ cachedUint8ArrayMemory0 = null;
406
+
407
+
408
+
409
+ return wasm;
410
+ }
411
+
412
+ function initSync(module) {
413
+ if (wasm !== undefined) return wasm;
414
+
415
+
416
+ if (typeof module !== 'undefined') {
417
+ if (Object.getPrototypeOf(module) === Object.prototype) {
418
+ ({module} = module)
419
+ } else {
420
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
421
+ }
422
+ }
423
+
424
+ const imports = __wbg_get_imports();
425
+
426
+ __wbg_init_memory(imports);
427
+
428
+ if (!(module instanceof WebAssembly.Module)) {
429
+ module = new WebAssembly.Module(module);
430
+ }
431
+
432
+ const instance = new WebAssembly.Instance(module, imports);
433
+
434
+ return __wbg_finalize_init(instance, module);
435
+ }
436
+
437
+ async function __wbg_init(module_or_path) {
438
+ if (wasm !== undefined) return wasm;
439
+
440
+
441
+ if (typeof module_or_path !== 'undefined') {
442
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
443
+ ({module_or_path} = module_or_path)
444
+ } else {
445
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
446
+ }
447
+ }
448
+
449
+ if (typeof module_or_path === 'undefined') {
450
+ module_or_path = new URL('k_centroid_scaler_bg.wasm', import.meta.url);
451
+ }
452
+ const imports = __wbg_get_imports();
453
+
454
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
455
+ module_or_path = fetch(module_or_path);
456
+ }
457
+
458
+ __wbg_init_memory(imports);
459
+
460
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
461
+
462
+ return __wbg_finalize_init(instance, module);
463
+ }
464
+
465
+ export { initSync };
466
+ export default __wbg_init;
Binary file
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "k-centroid-scaler",
3
+ "type": "module",
4
+ "version": "1.0.0",
5
+ "files": [
6
+ "k_centroid_scaler_bg.wasm",
7
+ "k_centroid_scaler.js"
8
+ ],
9
+ "main": "k_centroid_scaler.js",
10
+ "sideEffects": [
11
+ "./snippets/*"
12
+ ]
13
+ }