@mizchi/vlmkit-core 0.6.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/src/heatmap.ts ADDED
@@ -0,0 +1,516 @@
1
+ import type { VrtDiff, VrtSnapshot, DiffRegion, DiffRegionType, DiffReport, ShiftRegion } from "./types.ts";
2
+ import { type PngData, cropImage, decodePng, encodePng } from "./png-utils.ts";
3
+
4
+ // ---- Shared diff pipeline ----
5
+
6
+ interface PixelDiffResult {
7
+ diffOutput: Uint8Array;
8
+ width: number;
9
+ height: number;
10
+ diffPixels: number;
11
+ totalPixels: number;
12
+ threshold: number;
13
+ resizedBaseline: PngData;
14
+ resizedCurrent: PngData;
15
+ }
16
+
17
+ async function runPixelDiff(
18
+ baselinePath: string,
19
+ screenshotPath: string,
20
+ testId: string,
21
+ opts: { threshold?: number; outputDir?: string; skipHeatmap?: boolean },
22
+ ): Promise<PixelDiffResult & { heatmapPath?: string }> {
23
+ const pixelmatch = (await import("pixelmatch")).default;
24
+ const baseline = await decodePng(baselinePath);
25
+ const current = await decodePng(screenshotPath);
26
+
27
+ let resizedBaseline = baseline;
28
+ let resizedCurrent = current;
29
+ let overflowPixels = 0;
30
+
31
+ if (baseline.width !== current.width || baseline.height !== current.height) {
32
+ const commonW = Math.min(baseline.width, current.width);
33
+ const commonH = Math.min(baseline.height, current.height);
34
+ overflowPixels =
35
+ Math.max(baseline.width, current.width) * Math.max(baseline.height, current.height)
36
+ - commonW * commonH;
37
+ resizedBaseline = cropImage(baseline, commonW, commonH);
38
+ resizedCurrent = cropImage(current, commonW, commonH);
39
+ }
40
+
41
+ const width = resizedBaseline.width;
42
+ const height = resizedBaseline.height;
43
+ const totalPixels = width * height + overflowPixels;
44
+ const diffOutput = new Uint8Array(width * height * 4);
45
+ const threshold = opts.threshold ?? 0.1;
46
+
47
+ const diffPixels = overflowPixels + pixelmatch(
48
+ resizedBaseline.data, resizedCurrent.data, diffOutput, width, height, { threshold },
49
+ );
50
+
51
+ let heatmapPath: string | undefined;
52
+ if (opts.outputDir && diffPixels > 0 && !opts.skipHeatmap) {
53
+ const safeName = testId.replace(/[/\\:]/g, "_");
54
+ heatmapPath = `${opts.outputDir}/${safeName}_heatmap.png`;
55
+ await encodePng(heatmapPath, { width, height, data: diffOutput });
56
+ }
57
+
58
+ return { diffOutput, width, height, diffPixels, totalPixels, threshold, resizedBaseline, resizedCurrent, heatmapPath };
59
+ }
60
+
61
+ // ---- Public API ----
62
+
63
+ /**
64
+ * Compare two screenshots pixel-by-pixel and generate a diff heatmap.
65
+ */
66
+ export async function compareScreenshots(
67
+ snapshot: VrtSnapshot,
68
+ opts: {
69
+ threshold?: number;
70
+ outputDir?: string;
71
+ skipHeatmap?: boolean;
72
+ } = {}
73
+ ): Promise<VrtDiff | null> {
74
+ if (!snapshot.baselinePath) return null;
75
+
76
+ const r = await runPixelDiff(snapshot.baselinePath, snapshot.screenshotPath, snapshot.testId, opts);
77
+ const regions = detectDiffRegions(r.diffOutput, r.width, r.height);
78
+
79
+ return {
80
+ snapshot,
81
+ diffPixels: r.diffPixels,
82
+ totalPixels: r.totalPixels,
83
+ diffRatio: r.diffPixels / r.totalPixels,
84
+ heatmapPath: r.heatmapPath,
85
+ regions,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Grid-based diff region detection.
91
+ * Splits image into cells and clusters cells exceeding the diff threshold.
92
+ */
93
+ function detectDiffRegions(
94
+ diffData: Uint8Array,
95
+ width: number,
96
+ height: number,
97
+ cellSize: number = 32
98
+ ): DiffRegion[] {
99
+ const cols = Math.ceil(width / cellSize);
100
+ const rows = Math.ceil(height / cellSize);
101
+ const grid = new Uint32Array(cols * rows);
102
+
103
+ // Count diff pixels per cell
104
+ for (let y = 0; y < height; y++) {
105
+ for (let x = 0; x < width; x++) {
106
+ const idx = (y * width + x) * 4;
107
+ // pixelmatch diff: changed = red (R=255,G=0), unchanged = white (R=255,G=255)
108
+ if (diffData[idx + 1] < 128) {
109
+ const col = Math.floor(x / cellSize);
110
+ const row = Math.floor(y / cellSize);
111
+ grid[row * cols + col]++;
112
+ }
113
+ }
114
+ }
115
+
116
+ // Merge adjacent diff cells into bounding rectangles
117
+ const visited = new Uint8Array(cols * rows);
118
+ const regions: DiffRegion[] = [];
119
+ const minPixels = 4; // noise threshold
120
+
121
+ for (let r = 0; r < rows; r++) {
122
+ for (let c = 0; c < cols; c++) {
123
+ const i = r * cols + c;
124
+ if (visited[i] || grid[i] < minPixels) continue;
125
+
126
+ // BFS cluster detection
127
+ let minC = c,
128
+ maxC = c,
129
+ minR = r,
130
+ maxR = r;
131
+ let totalDiff = 0;
132
+ const queue = [i];
133
+ visited[i] = 1;
134
+
135
+ while (queue.length > 0) {
136
+ const ci = queue.shift()!;
137
+ const cr = Math.floor(ci / cols);
138
+ const cc = ci % cols;
139
+ totalDiff += grid[ci];
140
+ minC = Math.min(minC, cc);
141
+ maxC = Math.max(maxC, cc);
142
+ minR = Math.min(minR, cr);
143
+ maxR = Math.max(maxR, cr);
144
+
145
+ // 4-connected neighbors
146
+ for (const [dr, dc] of [
147
+ [-1, 0],
148
+ [1, 0],
149
+ [0, -1],
150
+ [0, 1],
151
+ ]) {
152
+ const nr = cr + dr;
153
+ const nc = cc + dc;
154
+ if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
155
+ const ni = nr * cols + nc;
156
+ if (!visited[ni] && grid[ni] >= minPixels) {
157
+ visited[ni] = 1;
158
+ queue.push(ni);
159
+ }
160
+ }
161
+ }
162
+
163
+ const regionWidth = (maxC - minC + 1) * cellSize;
164
+ const regionHeight = (maxR - minR + 1) * cellSize;
165
+ regions.push({
166
+ x: minC * cellSize,
167
+ y: minR * cellSize,
168
+ width: regionWidth,
169
+ height: regionHeight,
170
+ diffPixelCount: totalDiff,
171
+ regionType: classifyRegion(regionWidth, regionHeight, width),
172
+ });
173
+ }
174
+ }
175
+
176
+ return regions;
177
+ }
178
+
179
+ /**
180
+ * Classify a diff region based on its shape relative to the image width.
181
+ * - "edge": thin lines (height <= 2 or width <= 2)
182
+ * - "shift": wide horizontal bands (width/height > 3 and width > 80% image width)
183
+ * - "content": localized changes
184
+ */
185
+ function classifyRegion(regionWidth: number, regionHeight: number, imageWidth: number): DiffRegionType {
186
+ if (regionHeight <= 2 || regionWidth <= 2) return "edge";
187
+ if (regionWidth / regionHeight > 3 && regionWidth > imageWidth * 0.8) return "shift";
188
+ return "content";
189
+ }
190
+
191
+ /**
192
+ * Compute luminance profile (average brightness per row).
193
+ */
194
+ function luminanceProfile(data: Uint8Array, width: number, height: number): Float64Array {
195
+ const profile = new Float64Array(height);
196
+ for (let y = 0; y < height; y++) {
197
+ let sum = 0;
198
+ for (let x = 0; x < width; x++) {
199
+ const idx = (y * width + x) * 4;
200
+ sum += 0.299 * data[idx] + 0.587 * data[idx + 1] + 0.114 * data[idx + 2];
201
+ }
202
+ profile[y] = sum / width;
203
+ }
204
+ return profile;
205
+ }
206
+
207
+ /**
208
+ * Detect global vertical shift between two images using cross-correlation.
209
+ * Returns the offset in pixels (positive = img2 shifted down).
210
+ */
211
+ function detectGlobalShift(
212
+ baseline: { data: Uint8Array; width: number; height: number },
213
+ current: { data: Uint8Array; width: number; height: number },
214
+ maxShift?: number,
215
+ ): number {
216
+ const height = Math.min(baseline.height, current.height);
217
+ const width = Math.min(baseline.width, current.width);
218
+ const limit = maxShift ?? Math.min(Math.floor(height / 4), 500);
219
+
220
+ const profile1 = luminanceProfile(baseline.data, width, height);
221
+ const profile2 = luminanceProfile(current.data, width, height);
222
+
223
+ let bestOffset = 0;
224
+ let bestCorr = -Infinity;
225
+
226
+ for (let offset = -limit; offset <= limit; offset++) {
227
+ let sum = 0;
228
+ let count = 0;
229
+ for (let y = 0; y < height; y++) {
230
+ const y2 = y + offset;
231
+ if (y2 >= 0 && y2 < height) {
232
+ sum += profile1[y] * profile2[y2];
233
+ count++;
234
+ }
235
+ }
236
+ const corr = count > 0 ? sum / count : 0;
237
+ if (corr > bestCorr) {
238
+ bestCorr = corr;
239
+ bestOffset = offset;
240
+ }
241
+ }
242
+ return bestOffset;
243
+ }
244
+
245
+ /**
246
+ * Per-band shift detection — split the image into horizontal bands and run
247
+ * the same cross-correlation per band. Lets us report "section A shifted
248
+ * +8px, section B shifted +20px" instead of a single global average that
249
+ * loses localization.
250
+ *
251
+ * Bands with low luminance variance (e.g. a flat white footer) are dropped
252
+ * because cross-correlation can't lock onto them and the result is noise.
253
+ *
254
+ * Exported for unit testing.
255
+ */
256
+ export function detectBandShifts(
257
+ baseline: { data: Uint8Array; width: number; height: number },
258
+ current: { data: Uint8Array; width: number; height: number },
259
+ options: { bandHeight?: number; minConfidence?: number; maxShift?: number } = {},
260
+ ): ShiftRegion[] {
261
+ const height = Math.min(baseline.height, current.height);
262
+ const width = Math.min(baseline.width, current.width);
263
+ const bandHeight = Math.max(50, options.bandHeight ?? 240);
264
+ const minConfidence = options.minConfidence ?? 0.02;
265
+ const limit = options.maxShift ?? Math.min(Math.floor(bandHeight / 2), 400);
266
+
267
+ if (height < bandHeight * 2) return [];
268
+
269
+ const profile1 = luminanceProfile(baseline.data, width, height);
270
+ const profile2 = luminanceProfile(current.data, width, height);
271
+
272
+ const regions: ShiftRegion[] = [];
273
+ const bandCount = Math.floor(height / bandHeight);
274
+ for (let b = 0; b < bandCount; b++) {
275
+ const yStart = b * bandHeight;
276
+ const yEnd = b === bandCount - 1 ? height : yStart + bandHeight;
277
+
278
+ // Variance check — flat bands have no signal.
279
+ let mean = 0;
280
+ for (let y = yStart; y < yEnd; y++) mean += profile1[y]!;
281
+ mean /= (yEnd - yStart);
282
+ let variance = 0;
283
+ for (let y = yStart; y < yEnd; y++) {
284
+ const d = profile1[y]! - mean;
285
+ variance += d * d;
286
+ }
287
+ variance /= (yEnd - yStart);
288
+ if (variance < 5) continue; // empirically: flat background
289
+
290
+ // Mean-subtract both profiles so the cross-correlation magnitude scales
291
+ // with actual structure rather than background brightness.
292
+ let mean2 = 0;
293
+ for (let y = yStart; y < yEnd; y++) mean2 += profile2[y]!;
294
+ mean2 /= (yEnd - yStart);
295
+
296
+ let bestOffset = 0;
297
+ let bestCorr = -Infinity;
298
+ let secondBestCorr = -Infinity;
299
+ let zeroOffsetCorr = 0;
300
+ for (let offset = -limit; offset <= limit; offset++) {
301
+ let sum = 0;
302
+ let count = 0;
303
+ for (let y = yStart; y < yEnd; y++) {
304
+ const y2 = y + offset;
305
+ if (y2 >= 0 && y2 < height) {
306
+ sum += (profile1[y]! - mean) * (profile2[y2]! - mean2);
307
+ count++;
308
+ }
309
+ }
310
+ const corr = count > 0 ? sum / count : 0;
311
+ if (offset === 0) zeroOffsetCorr = corr;
312
+ if (corr > bestCorr) {
313
+ secondBestCorr = bestCorr;
314
+ bestCorr = corr;
315
+ bestOffset = offset;
316
+ } else if (corr > secondBestCorr) {
317
+ secondBestCorr = corr;
318
+ }
319
+ }
320
+
321
+ // Confidence = peak sharpness relative to the second-best alignment.
322
+ // A clean shift has best ≫ second-best; noise has best ≈ second-best.
323
+ const confidence = bestCorr > 0 && secondBestCorr > 0
324
+ ? Math.min(1, Math.max(0, (bestCorr - secondBestCorr) / bestCorr))
325
+ : 0;
326
+
327
+ if (bestOffset !== 0 && bestCorr > zeroOffsetCorr && confidence >= minConfidence) {
328
+ regions.push({ yStart, yEnd, shift: bestOffset, confidence: Number(confidence.toFixed(3)) });
329
+ }
330
+ }
331
+
332
+ return regions;
333
+ }
334
+
335
+ /**
336
+ * Count diff pixels after compensating for vertical shift.
337
+ */
338
+ function compensatedDiffCount(
339
+ baselineData: Uint8Array,
340
+ currentData: Uint8Array,
341
+ width: number,
342
+ height: number,
343
+ shift: number,
344
+ threshold: number,
345
+ ): number {
346
+ let count = 0;
347
+ for (let y = 0; y < height; y++) {
348
+ const y2 = y + shift;
349
+ if (y2 < 0 || y2 >= height) {
350
+ count += width;
351
+ continue;
352
+ }
353
+ for (let x = 0; x < width; x++) {
354
+ const idx1 = (y * width + x) * 4;
355
+ const idx2 = (y2 * width + x) * 4;
356
+ const dr = Math.abs(baselineData[idx1] - currentData[idx2]);
357
+ const dg = Math.abs(baselineData[idx1 + 1] - currentData[idx2 + 1]);
358
+ const db = Math.abs(baselineData[idx1 + 2] - currentData[idx2 + 2]);
359
+ if ((dr + dg + db) / 3 > threshold * 255) count++;
360
+ }
361
+ }
362
+ return count;
363
+ }
364
+
365
+ /**
366
+ * Generate a compact 10x10 ASCII heatmap of diff distribution.
367
+ */
368
+ function generateCompact(
369
+ diffData: Uint8Array,
370
+ width: number,
371
+ height: number,
372
+ diffPixels: number,
373
+ totalPixels: number,
374
+ regions: DiffRegion[],
375
+ ): string {
376
+ const gridSize = 10;
377
+ const cellW = Math.ceil(width / gridSize);
378
+ const cellH = Math.ceil(height / gridSize);
379
+ const grid: number[][] = Array.from({ length: gridSize }, () => new Array(gridSize).fill(0));
380
+
381
+ for (let y = 0; y < height; y++) {
382
+ for (let x = 0; x < width; x++) {
383
+ const idx = (y * width + x) * 4;
384
+ // pixelmatch diff output: changed pixels are red (R=255,G=0,B=0),
385
+ // unchanged pixels are white (R=255,G=255,B=255). Check G channel.
386
+ if (diffData[idx + 1] < 128) {
387
+ const gx = Math.min(Math.floor(x / cellW), gridSize - 1);
388
+ const gy = Math.min(Math.floor(y / cellH), gridSize - 1);
389
+ grid[gy][gx]++;
390
+ }
391
+ }
392
+ }
393
+
394
+ const matchPct = ((1 - diffPixels / totalPixels) * 100).toFixed(0);
395
+ const lines = [`diff:${diffPixels}/${totalPixels}(${matchPct}%match)`];
396
+ const cellTotal = cellW * cellH;
397
+ for (let gy = 0; gy < gridSize; gy++) {
398
+ lines.push(grid[gy].map((v) => (v > cellTotal * 0.05 ? "X" : ".")).join(""));
399
+ }
400
+ if (regions.length > 0) {
401
+ const regionStrs = regions.map((r) => `${r.regionType || "content"}:${r.x},${r.y},${r.width}x${r.height}`);
402
+ lines.push(`regions:${regionStrs.join(";")}`);
403
+ }
404
+ return lines.join("\n");
405
+ }
406
+
407
+ /**
408
+ * Generate a comprehensive diff report including clustering, shift detection,
409
+ * and region classification. Compatible with mizchi/pixelmatch 0.5.0 DiffReport format.
410
+ */
411
+ export async function generateDiffReport(
412
+ snapshot: VrtSnapshot,
413
+ opts: {
414
+ threshold?: number;
415
+ outputDir?: string;
416
+ skipHeatmap?: boolean;
417
+ detectShift?: boolean;
418
+ } = {},
419
+ ): Promise<DiffReport | null> {
420
+ if (!snapshot.baselinePath) return null;
421
+
422
+ const r = await runPixelDiff(snapshot.baselinePath, snapshot.screenshotPath, snapshot.testId, opts);
423
+ const regions = detectDiffRegions(r.diffOutput, r.width, r.height);
424
+
425
+ // Shift detection
426
+ let globalShift = 0;
427
+ let shiftRegions: ShiftRegion[] = [];
428
+ let compensated = r.diffPixels;
429
+
430
+ if (opts.detectShift !== false && r.height > 4) {
431
+ globalShift = detectGlobalShift(r.resizedBaseline, r.resizedCurrent);
432
+ if (globalShift !== 0) {
433
+ compensated = compensatedDiffCount(
434
+ r.resizedBaseline.data, r.resizedCurrent.data,
435
+ r.width, r.height, globalShift, r.threshold,
436
+ );
437
+ // Prefer per-band shifts when they reveal locally-varying offsets.
438
+ // Falls back to the global single-band region if no band locks on.
439
+ const bands = detectBandShifts(r.resizedBaseline, r.resizedCurrent);
440
+ shiftRegions = bands.length > 0
441
+ ? bands
442
+ : [{ yStart: 0, yEnd: r.height, shift: globalShift }];
443
+ }
444
+ }
445
+
446
+ const shiftOnly = regions.length > 0 && regions.every((rg) => rg.regionType === "shift" || rg.regionType === "edge");
447
+ const contentChangeCount = regions.filter((rg) => rg.regionType === "content").length;
448
+ const compact = generateCompact(r.diffOutput, r.width, r.height, r.diffPixels, r.totalPixels, regions);
449
+
450
+ return {
451
+ diffPixels: r.diffPixels,
452
+ totalPixels: r.totalPixels,
453
+ diffRatio: r.diffPixels / r.totalPixels,
454
+ regions,
455
+ shiftOnly,
456
+ contentChangeCount,
457
+ globalShift,
458
+ shiftRegions,
459
+ compensatedDiffCount: compensated,
460
+ compact,
461
+ };
462
+ }
463
+
464
+ /**
465
+ * Whiteout detection: checks if most of the image is white (or a single color).
466
+ */
467
+ export function detectWhiteout(
468
+ data: PngData,
469
+ opts: { threshold?: number } = {}
470
+ ): { isWhiteout: boolean; whiteRatio: number } {
471
+ const threshold = opts.threshold ?? 0.95;
472
+ const { width, height, data: pixels } = data;
473
+ const total = width * height;
474
+ let whiteCount = 0;
475
+
476
+ for (let i = 0; i < total; i++) {
477
+ const offset = i * 4;
478
+ const r = pixels[offset];
479
+ const g = pixels[offset + 1];
480
+ const b = pixels[offset + 2];
481
+ // Treat (250+, 250+, 250+) as white
482
+ if (r >= 250 && g >= 250 && b >= 250) {
483
+ whiteCount++;
484
+ }
485
+ }
486
+
487
+ const whiteRatio = whiteCount / total;
488
+ return { isWhiteout: whiteRatio >= threshold, whiteRatio };
489
+ }
490
+
491
+ /**
492
+ * Empty content detection: checks if the image has low entropy.
493
+ */
494
+ export function detectEmptyContent(
495
+ data: PngData,
496
+ opts: { threshold?: number } = {}
497
+ ): { isEmpty: boolean; uniqueColors: number } {
498
+ const threshold = opts.threshold ?? 8;
499
+ const colorSet = new Set<number>();
500
+ const { width, height, data: pixels } = data;
501
+ const total = width * height;
502
+
503
+ // Sampling with stride (full scan is too expensive)
504
+ const stride = Math.max(1, Math.floor(total / 10000));
505
+ for (let i = 0; i < total; i += stride) {
506
+ const offset = i * 4;
507
+ const color =
508
+ (pixels[offset] << 16) | (pixels[offset + 1] << 8) | pixels[offset + 2];
509
+ colorSet.add(color);
510
+ }
511
+
512
+ return {
513
+ isEmpty: colorSet.size <= threshold,
514
+ uniqueColors: colorSet.size,
515
+ };
516
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Image resize + VLM optimization
3
+ *
4
+ * Downscale images before sending to VLM to reduce token cost.
5
+ * Supports auto-escalation when resolution is insufficient.
6
+ */
7
+ import { PNG } from "pngjs";
8
+
9
+ export type ResolutionPreset = "low" | "medium" | "high" | "full";
10
+
11
+ export const RESOLUTION_PRESETS: Record<ResolutionPreset, { maxWidth: number; maxHeight: number }> = {
12
+ low: { maxWidth: 375, maxHeight: 320 }, // mobile viewport width. ~130 tokens
13
+ medium: { maxWidth: 640, maxHeight: 480 }, // breakpoint boundary. ~200 tokens
14
+ high: { maxWidth: 1280, maxHeight: 900 }, // desktop viewport. ~500 tokens
15
+ full: { maxWidth: 4096, maxHeight: 4096 }, // original size
16
+ };
17
+
18
+ /**
19
+ * Select the optimal resolution preset for a given viewport width.
20
+ * Returns the smallest preset with at least half the viewport width.
21
+ */
22
+ export function resolveResolutionForViewport(
23
+ viewportWidth: number,
24
+ maxPreset: ResolutionPreset = "high",
25
+ ): ResolutionPreset {
26
+ const order: ResolutionPreset[] = ["low", "medium", "high", "full"];
27
+ const maxIdx = order.indexOf(maxPreset);
28
+
29
+ for (let i = 0; i <= maxIdx; i++) {
30
+ const preset = RESOLUTION_PRESETS[order[i]];
31
+ // Sufficient if image width >= half of viewport
32
+ if (preset.maxWidth >= viewportWidth / 2) return order[i];
33
+ }
34
+
35
+ return maxPreset;
36
+ }
37
+
38
+ export interface ResizeOptions {
39
+ /** Preset or custom size */
40
+ resolution?: ResolutionPreset | { maxWidth: number; maxHeight: number };
41
+ }
42
+
43
+ /** Resize PNG buffer to fit within the given size. Preserves aspect ratio. */
44
+ export function resizePngBuffer(pngBuffer: Buffer, options: ResizeOptions = {}): Buffer {
45
+ const preset = typeof options.resolution === "string"
46
+ ? RESOLUTION_PRESETS[options.resolution]
47
+ : options.resolution ?? RESOLUTION_PRESETS.medium;
48
+
49
+ const src = PNG.sync.read(pngBuffer);
50
+
51
+ if (src.width <= preset.maxWidth && src.height <= preset.maxHeight) {
52
+ return pngBuffer; // already small enough
53
+ }
54
+
55
+ const scale = Math.min(preset.maxWidth / src.width, preset.maxHeight / src.height);
56
+ const targetW = Math.round(src.width * scale);
57
+ const targetH = Math.round(src.height * scale);
58
+
59
+ const dst = new PNG({ width: targetW, height: targetH });
60
+ const xRatio = src.width / targetW;
61
+ const yRatio = src.height / targetH;
62
+
63
+ for (let y = 0; y < targetH; y++) {
64
+ for (let x = 0; x < targetW; x++) {
65
+ const srcX = Math.min(Math.floor(x * xRatio), src.width - 1);
66
+ const srcY = Math.min(Math.floor(y * yRatio), src.height - 1);
67
+ const si = (srcY * src.width + srcX) * 4;
68
+ const di = (y * targetW + x) * 4;
69
+ dst.data[di] = src.data[si];
70
+ dst.data[di + 1] = src.data[si + 1];
71
+ dst.data[di + 2] = src.data[si + 2];
72
+ dst.data[di + 3] = src.data[si + 3];
73
+ }
74
+ }
75
+
76
+ return Buffer.from(PNG.sync.write(dst));
77
+ }
78
+
79
+ /** Read dimensions from PNG IHDR chunk (no full decode needed) */
80
+ function readPngDimensions(buf: Buffer): { width: number; height: number } {
81
+ // PNG header: 8-byte signature, then IHDR chunk: 4-byte length, 4-byte type, 4-byte width, 4-byte height
82
+ if (buf.length >= 24 && buf[0] === 0x89 && buf[1] === 0x50) {
83
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
84
+ }
85
+ // Fallback: full decode
86
+ const png = PNG.sync.read(buf);
87
+ return { width: png.width, height: png.height };
88
+ }
89
+
90
+ /** Resize a base64 PNG to the specified resolution. Returns base64. */
91
+ export function resizeBase64Png(base64: string, options: ResizeOptions = {}): string {
92
+ const preset = typeof options.resolution === "string"
93
+ ? RESOLUTION_PRESETS[options.resolution]
94
+ : options.resolution ?? RESOLUTION_PRESETS.medium;
95
+
96
+ const buf = Buffer.from(base64, "base64");
97
+ const { width, height } = readPngDimensions(buf);
98
+
99
+ // Skip round-trip if already small enough
100
+ if (width <= preset.maxWidth && height <= preset.maxHeight) {
101
+ return base64;
102
+ }
103
+
104
+ const resized = resizePngBuffer(buf, options);
105
+ return resized.toString("base64");
106
+ }
107
+
108
+ /** Get image dimensions */
109
+ export function getImageDimensions(base64: string): { width: number; height: number } {
110
+ const buf = Buffer.from(base64, "base64");
111
+ return readPngDimensions(buf);
112
+ }