feat(importer): phase 1 — resize controls with multiple methods

Add W/H inputs, aspect-ratio lock, resampling method dropdown (nearest /
bilinear / box), "Fit to canvas" (respects current origin) and "1:1" reset
buttons to the import panel. Pipeline now runs resize before palette
quantization so dither/skip-matching operate on the final dimensions.

Shared src/lib/image-resize.js is reused by scripts/image-to-colors.js,
which gains --width, --height, --method flags with aspect-preserve when
only one dimension is provided.
This commit is contained in:
tiennm99 committed 2026-04-17 11:43:11 +07:00
1 parent 9254fec8c9
commit f94f1dc5f5
4 files changed
+310 -19

No files matched your search

+75 -12
View File
@@ -1,6 +1,7 @@
<script>
import { CANVAS_WIDTH, CANVAS_HEIGHT } from '../../lib/constants.js';
import { rgbaToPalette, paletteToRgba } from '../../lib/image-to-palette.js';
import { resizeRgba } from '../../lib/image-resize.js';
import { createImageUploader } from '../../lib/image-uploader.js';
let { open, cursorPos, getCommittedColor, onClose, onCredits } = $props();
@@ -24,6 +25,12 @@
let skipMatching = $state(true);
let dither = $state(false);
// Resize controls — init to source dims on file load
let resizeW = $state(0);
let resizeH = $state(0);
let lockAspect = $state(true);
let resampleMethod = $state('nearest'); // 'nearest' | 'bilinear' | 'box'
// Run state
let status = $state('idle'); // 'idle' | 'running' | 'paused' | 'done' | 'error'
let placed = $state(0);
@@ -57,6 +64,8 @@
srcRgba = data;
srcWidth = w;
srcHeight = h;
resizeW = w;
resizeH = h;
// paletteIndices recomputed reactively via $effect below.
} catch (err) {
errorText = `Failed to load image: ${err.message || err}`;
@@ -66,10 +75,15 @@
}
}
// Re-quantize when source or dither mode changes.
// Re-run pipeline when source / resize / dither / method changes.
$effect(() => {
if (!srcRgba) { paletteIndices = null; opaqueCount = 0; return; }
const idx = rgbaToPalette(srcRgba, srcWidth, srcHeight, { dither });
if (!srcRgba || resizeW <= 0 || resizeH <= 0) {
paletteIndices = null; opaqueCount = 0; return;
}
const working = (resizeW === srcWidth && resizeH === srcHeight)
? srcRgba
: resizeRgba(srcRgba, srcWidth, srcHeight, resizeW, resizeH, resampleMethod);
const idx = rgbaToPalette(working, resizeW, resizeH, { dither });
paletteIndices = idx;
let count = 0;
for (let i = 0; i < idx.length; i++) if (idx[i] >= 0) count++;
@@ -79,11 +93,40 @@
function renderPreview() {
if (!previewEl || !paletteIndices) return;
const rgba = paletteToRgba(paletteIndices, srcWidth, srcHeight);
previewEl.width = srcWidth;
previewEl.height = srcHeight;
const rgba = paletteToRgba(paletteIndices, resizeW, resizeH);
previewEl.width = resizeW;
previewEl.height = resizeH;
const ctx = previewEl.getContext('2d');
ctx.putImageData(new ImageData(rgba, srcWidth, srcHeight), 0, 0);
ctx.putImageData(new ImageData(rgba, resizeW, resizeH), 0, 0);
}
function onResizeWInput(e) {
const v = parseInt(e.target.value, 10);
if (!Number.isFinite(v) || v < 1) return;
resizeW = Math.min(CANVAS_WIDTH, v);
if (lockAspect && srcWidth > 0) {
resizeH = Math.max(1, Math.min(CANVAS_HEIGHT, Math.round(srcHeight * resizeW / srcWidth)));
}
}
function onResizeHInput(e) {
const v = parseInt(e.target.value, 10);
if (!Number.isFinite(v) || v < 1) return;
resizeH = Math.min(CANVAS_HEIGHT, v);
if (lockAspect && srcHeight > 0) {
resizeW = Math.max(1, Math.min(CANVAS_WIDTH, Math.round(srcWidth * resizeH / srcHeight)));
}
}
function fitToCanvas() {
if (!srcWidth || !srcHeight) return;
const maxW = Math.max(1, CANVAS_WIDTH - originX);
const maxH = Math.max(1, CANVAS_HEIGHT - originY);
const ratio = Math.min(maxW / srcWidth, maxH / srcHeight, 1);
resizeW = Math.max(1, Math.floor(srcWidth * ratio));
resizeH = Math.max(1, Math.floor(srcHeight * ratio));
}
function resetSize() {
resizeW = srcWidth;
resizeH = srcHeight;
}
$effect(() => { if (open && paletteIndices) renderPreview(); });
@@ -97,7 +140,7 @@
if (!paletteIndices) return 'No image loaded.';
if (!Number.isInteger(originX) || !Number.isInteger(originY)) return 'X and Y must be integers.';
if (originX < 0 || originY < 0) return 'X and Y must be ≥ 0.';
if (originX + srcWidth > CANVAS_WIDTH || originY + srcHeight > CANVAS_HEIGHT) {
if (originX + resizeW > CANVAS_WIDTH || originY + resizeH > CANVAS_HEIGHT) {
return `Image would overflow canvas (${CANVAS_WIDTH}x${CANVAS_HEIGHT}).`;
}
return null;
@@ -108,8 +151,8 @@
for (let i = 0; i < paletteIndices.length; i++) {
const color = paletteIndices[i];
if (color < 0) continue;
const lx = i % srcWidth;
const ly = (i / srcWidth) | 0;
const lx = i % resizeW;
const ly = (i / resizeW) | 0;
const x = originX + lx;
const y = originY + ly;
if (skipMatching && getCommittedColor?.(x, y) === color) continue;
@@ -197,11 +240,29 @@
<canvas bind:this={previewEl} class="preview"></canvas>
</div>
<div class="meta">
<div>{srcWidth} × {srcHeight}</div>
<div>{opaqueCount} / {srcWidth * srcHeight} opaque</div>
<div>source: {srcWidth} × {srcHeight}</div>
<div>output: {resizeW} × {resizeH}</div>
<div>{opaqueCount} / {resizeW * resizeH} opaque</div>
</div>
</div>
<div class="row">
<label>W <input type="number" min="1" max={CANVAS_WIDTH} value={resizeW} oninput={onResizeWInput} /></label>
<label>H <input type="number" min="1" max={CANVAS_HEIGHT} value={resizeH} oninput={onResizeHInput} /></label>
<label class="chk" title="Lock aspect ratio to source"><input type="checkbox" bind:checked={lockAspect} /> lock</label>
</div>
<div class="row">
<label>Method
<select bind:value={resampleMethod}>
<option value="nearest">nearest</option>
<option value="bilinear">bilinear</option>
<option value="box">box</option>
</select>
</label>
<button onclick={fitToCanvas} title="Fit within canvas at current origin">Fit</button>
<button onclick={resetSize} title="Reset to source dimensions">1:1</button>
</div>
<div class="row">
<label>X <input type="number" min="0" max={CANVAS_WIDTH - 1} bind:value={originX} /></label>
<label>Y <input type="number" min="0" max={CANVAS_HEIGHT - 1} bind:value={originY} /></label>
@@ -279,6 +340,8 @@
label { display: flex; align-items: center; gap: 6px; }
input[type="number"] { width: 70px; padding: 4px 6px; background: #1a1a1a; border: 1px solid #444; color: #eee; border-radius: 4px; }
select { padding: 4px 6px; background: #1a1a1a; border: 1px solid #444; color: #eee; border-radius: 4px; }
.chk { font-size: 0.8rem; color: #aaa; cursor: pointer; }
.file-btn {
display: inline-block; padding: 6px 12px; background: #2563eb; border-radius: 6px;
+112
View File
@@ -0,0 +1,112 @@
/**
* Pure RGBA buffer resizers. No DOM dependency — usable in both the browser
* importer and the Node CLI (with a sharp-provided RGBA input).
*
* All methods return a fresh Uint8ClampedArray of length dstW*dstH*4.
* If src dimensions match dst, returns a copy (identity).
*/
/**
* @param {Uint8Array|Uint8ClampedArray|number[]} rgba - src RGBA (length = srcW*srcH*4)
* @param {number} srcW
* @param {number} srcH
* @param {number} dstW
* @param {number} dstH
* @param {'nearest'|'bilinear'|'box'} [method='nearest']
* @returns {Uint8ClampedArray}
*/
export function resizeRgba(rgba, srcW, srcH, dstW, dstH, method = 'nearest') {
if (dstW <= 0 || dstH <= 0) throw new Error('dstW and dstH must be > 0');
if (srcW === dstW && srcH === dstH) return new Uint8ClampedArray(rgba);
switch (method) {
case 'bilinear': return resampleBilinear(rgba, srcW, srcH, dstW, dstH);
case 'box': return resampleBox(rgba, srcW, srcH, dstW, dstH);
case 'nearest':
default: return resampleNearest(rgba, srcW, srcH, dstW, dstH);
}
}
function resampleNearest(src, sw, sh, dw, dh) {
const out = new Uint8ClampedArray(dw * dh * 4);
const xRatio = sw / dw;
const yRatio = sh / dh;
for (let y = 0; y < dh; y++) {
const sy = Math.min(sh - 1, (y * yRatio) | 0);
for (let x = 0; x < dw; x++) {
const sx = Math.min(sw - 1, (x * xRatio) | 0);
const si = (sy * sw + sx) * 4;
const di = (y * dw + x) * 4;
out[di] = src[si];
out[di + 1] = src[si + 1];
out[di + 2] = src[si + 2];
out[di + 3] = src[si + 3];
}
}
return out;
}
function resampleBilinear(src, sw, sh, dw, dh) {
const out = new Uint8ClampedArray(dw * dh * 4);
const xRatio = dw > 1 ? (sw - 1) / (dw - 1) : 0;
const yRatio = dh > 1 ? (sh - 1) / (dh - 1) : 0;
for (let y = 0; y < dh; y++) {
const fy = y * yRatio;
const y0 = fy | 0;
const y1 = Math.min(sh - 1, y0 + 1);
const wy = fy - y0;
for (let x = 0; x < dw; x++) {
const fx = x * xRatio;
const x0 = fx | 0;
const x1 = Math.min(sw - 1, x0 + 1);
const wx = fx - x0;
const i00 = (y0 * sw + x0) * 4;
const i01 = (y0 * sw + x1) * 4;
const i10 = (y1 * sw + x0) * 4;
const i11 = (y1 * sw + x1) * 4;
const di = (y * dw + x) * 4;
for (let c = 0; c < 4; c++) {
const top = src[i00 + c] * (1 - wx) + src[i01 + c] * wx;
const bottom = src[i10 + c] * (1 - wx) + src[i11 + c] * wx;
out[di + c] = top * (1 - wy) + bottom * wy;
}
}
}
return out;
}
/** Box filter: average pixels in each destination cell's source footprint.
* Good for downscales; degrades to nearest for upscales (footprint < 1 pixel). */
function resampleBox(src, sw, sh, dw, dh) {
if (dw >= sw || dh >= sh) return resampleBilinear(src, sw, sh, dw, dh);
const out = new Uint8ClampedArray(dw * dh * 4);
const xRatio = sw / dw;
const yRatio = sh / dh;
for (let y = 0; y < dh; y++) {
const sy0 = Math.floor(y * yRatio);
const sy1 = Math.min(sh, Math.ceil((y + 1) * yRatio));
for (let x = 0; x < dw; x++) {
const sx0 = Math.floor(x * xRatio);
const sx1 = Math.min(sw, Math.ceil((x + 1) * xRatio));
let r = 0, g = 0, b = 0, a = 0, n = 0;
for (let yy = sy0; yy < sy1; yy++) {
for (let xx = sx0; xx < sx1; xx++) {
const si = (yy * sw + xx) * 4;
r += src[si];
g += src[si + 1];
b += src[si + 2];
a += src[si + 3];
n++;
}
}
const di = (y * dw + x) * 4;
out[di] = r / n;
out[di + 1] = g / n;
out[di + 2] = b / n;
out[di + 3] = a / n;
}
}
return out;
}