From 6ba77ff867398f899e8bc63f129f7bd2f9d08229 Mon Sep 17 00:00:00 2001 From: Harshit Shah Date: Wed, 2 Dec 2026 20:38:48 +0530 Subject: [PATCH 1/2] fix(padfit): crop App Live phone frame and add viewfinder calibration Screenshots from the App Live dashboard can include the dark phone frame, and PadFit then picked the whole screen as the viewfinder. PadFit now crops to the screen inside the frame first. Some apps show a different part of the camera image in the viewfinder than the box position on screen suggests (SITA Kenya eTA: box at about 17-46% of the screen, shows 32-66% of the image). Optional calibration: inject a colour grid, screenshot the camera screen, and PadFit reads which part of the image the viewfinder shows, then places the subject there. Co-Authored-By: Claude Opus 5.5 --- docs/tools/image-padding/index.html | 248 ++++++++++++++++++++++++++-- 1 file changed, 235 insertions(+), 13 deletions(-) diff --git a/docs/tools/image-padding/index.html b/docs/tools/image-padding/index.html index 7bcc3b4..5f0023d 100644 --- a/docs/tools/image-padding/index.html +++ b/docs/tools/image-padding/index.html @@ -111,6 +111,23 @@ +
+
Calibrate (optional)
+

Use this when the scanner still fails. Some apps show a different part of the camera image in the viewfinder.

+
    +
  1. Download the grid. Inject it into the app.
  2. +
  3. Open the same camera screen so the grid shows in the viewfinder (on Android, turn on Camera Preview). Take a screenshot.
  4. +
  5. Add that screenshot here.
  6. +
+ + + +
+
Subject
@@ -150,7 +167,7 @@
1 · ScreenshotGreen line = viewfinder found
2 · Image to injectGreen line = subject. Drag to draw. Drag inside your shape to move it, scroll to resize
3 · OutputSame size as the screenshot. Grey = padding
-
4 · CheckOutput over the screenshot. Drag to move
+
4 · CheckOutput over the screenshot. Drag to move
@@ -247,6 +264,37 @@ return best; } + // A capture of the whole device (App Live's phone frame) has a thin dark ring around the screen. + // Returns the screen inside that ring as [x, y, w, h], or null when there is no such ring. + function screenRect(rgba) { + const gray = M(new cv.Mat()), dark = M(new cv.Mat()); + cv.cvtColor(rgba, gray, cv.COLOR_RGBA2GRAY); + cv.threshold(gray, dark, 60, 255, cv.THRESH_BINARY_INV); + const W = gray.cols, H = gray.rows; + const { lab, comps } = components(dark, 8); + M(lab); + const ring = comps.find((c) => c.w >= 0.9 * W && c.h >= 0.9 * H && c.n < 0.25 * c.w * c.h); + let rect = null; + if (ring) { + const ringMask = M(new cv.Mat()); + const id = M(new cv.Mat(H, W, cv.CV_32S, new cv.Scalar(ring.id))); + cv.inRange(lab, id, id, ringMask); + const cs = M(new cv.MatVector()), hier = M(new cv.Mat()); + cv.findContours(ringMask, cs, hier, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE); + const phone = M(cv.Mat.zeros(H, W, cv.CV_8U)); + cv.drawContours(phone, cs, -1, new cv.Scalar(255), -1); + const inside = M(new cv.Mat()); + cv.subtract(phone, ringMask, inside); + if (cv.countNonZero(inside)) { + const b = cv.boundingRect(inside), edge = 0.01 * Math.min(W, H); + const framedAllSides = Math.min(b.x, b.y, W - b.x - b.width, H - b.y - b.height) >= edge; + if (framedAllSides && b.width >= 0.8 * ring.w && b.height >= 0.8 * ring.h) rect = [b.x + 1, b.y + 1, b.width - 2, b.height - 2]; + } + } + free(); + return rect; + } + // returns {result, mask} where mask is a full-resolution 8U viewfinder mask (convex) function viewfinder(rgba) { const step = 2; @@ -316,6 +364,127 @@ return { result, mask: up, hull }; } + // ---------- calibration: which part of the injected image the app shows in its viewfinder ---------- + const GRID_STEP = 0.1; + + function calibrationGrid(W, H) { + const g = new cv.Mat(H, W, cv.CV_8UC4), d = g.data; + for (let y = 0; y < H; y++) { + const r = Math.round(255 * y / (H - 1)); + for (let x = 0; x < W; x++) { + const i = 4 * (y * W + x); + d[i] = r; d[i + 1] = Math.round(255 * x / (W - 1)); d[i + 2] = 255; d[i + 3] = 255; + } + } + const lw = Math.max(4, Math.round(0.012 * Math.min(W, H))), black = new cv.Scalar(0, 0, 0, 255); + const font = Math.min(W, H) / 900; + for (let k = 1; k * GRID_STEP < 1 - 1e-9; k++) { + const y = Math.round(k * GRID_STEP * H), x = Math.round(k * GRID_STEP * W); + cv.line(g, new cv.Point(0, y), new cv.Point(W, y), black, lw); + cv.line(g, new cv.Point(x, 0), new cv.Point(x, H), black, lw); + for (const lx of [0.02, 0.52]) cv.putText(g, `${k * 10}%`, new cv.Point(Math.round(lx * W), y - 2 * lw), cv.FONT_HERSHEY_SIMPLEX, font, black, Math.max(1, Math.round(font * 2))); + } + return g; + } + + // One axis of the calibration screenshot. vals[p] is the colour ratio along the profile, dark[p] the share + // of dark pixels across it. Returns image fraction = a + s * p, p in screenshot pixels. + function fitAxis(vals, dark) { + const pts = vals.map((v, p) => [p, v]).filter(([, v]) => v !== null); + if (pts.length < 10) return null; + const n = pts.length, mx = pts.reduce((t, [p]) => t + p, 0) / n, my = pts.reduce((t, [, v]) => t + v, 0) / n; + let sxy = 0, sxx = 0; + for (const [p, v] of pts) { sxy += (p - mx) * (v - my); sxx += (p - mx) ** 2; } + let s = sxy / sxx, a = my - s * mx, lines = 0; + const centres = []; + for (let p = 0; p < dark.length;) { + if (dark[p] < 0.6) { p++; continue; } + let q = p; while (q < dark.length && dark[q] >= 0.6) q++; + if (p > 0 && q < dark.length) centres.push((p + q - 1) / 2); + p = q; + } + // Number the lines together, not one by one: they are evenly spaced, and only 1..9 tenths exist. + let marks = []; + if (centres.length >= 2) { + const gaps = centres.slice(1).map((c, i) => c - centres[i]).sort((p, q) => p - q), gap = gaps[gaps.length >> 1]; + const idx = centres.map((c) => Math.round((c - centres[0]) / gap)), dir = Math.sign(s); + const last = 1 / GRID_STEP - 1, span = Math.max(...idx); + let k0 = Math.round(centres.reduce((t, c, j) => t + (a + s * c) / GRID_STEP - dir * idx[j], 0) / centres.length); + k0 = dir > 0 ? Math.min(Math.max(k0, 1), last - span) : Math.min(Math.max(k0, 1 + span), last); + marks = centres.map((c, j) => [c, (k0 + dir * idx[j]) * GRID_STEP]); + } else if (centres.length === 1) { + marks = [[centres[0], Math.round((a + s * centres[0]) / GRID_STEP) * GRID_STEP]]; + } + if (marks.length >= 2) { + const lm = marks.length, cx = marks.reduce((t, [c]) => t + c, 0) / lm, cf = marks.reduce((t, [, f]) => t + f, 0) / lm; + let num = 0, den = 0; + for (const [c, f] of marks) { num += (c - cx) * (f - cf); den += (c - cx) ** 2; } + const sl = num / den; + if (Math.sign(sl) === Math.sign(s) && Math.abs(sl / s - 1) < 0.35) { s = sl; a = cf - s * cx; lines = lm; } + } else if (marks.length === 1) { + a = marks[0][1] - s * marks[0][0]; lines = 1; + } + return { a, s, lines }; + } + + // calib: RGBA screenshot of the app with the calibration grid injected and the camera preview on. + // win: [x, y, w, h] of the viewfinder in the same screenshot. Returns how screenshot pixels map to + // fractions of the injected image, or null when the grid is not visible in the viewfinder. + function readCalibration(calib, win) { + const [wx, wy, ww, wh] = win, ix = Math.round(0.04 * ww), iy = Math.round(0.04 * wh); + const x0 = wx + ix, y0 = wy + iy, x1 = wx + ww - ix, y1 = wy + wh - iy, W = calib.cols, d = calib.data; + const blues = []; + for (let y = y0; y < y1; y += 3) for (let x = x0; x < x1; x += 3) blues.push(d[4 * (y * W + x) + 2]); + blues.sort((p, q) => p - q); + const top = blues[Math.floor(0.9 * (blues.length - 1))] || 0; + if (top < 80) return null; + // Black lines are the zero point: this cancels a colour range shift or a dimmed preview. + const blacks = [[], [], []]; + for (let y = y0; y < y1; y += 2) for (let x = x0; x < x1; x += 2) { + const i = 4 * (y * W + x); if (d[i + 2] < 0.5 * top) { blacks[0].push(d[i]); blacks[1].push(d[i + 1]); blacks[2].push(d[i + 2]); } + } + const zero = blacks.map((a) => { if (!a.length) return 0; a.sort((p, q) => p - q); return a[a.length >> 1]; }); + const rows = [], rowDark = [], cols = [], colDark = new Array(x1 - x0).fill(0), colN = new Array(x1 - x0).fill(0); + const colVals = Array.from({ length: x1 - x0 }, () => []); + const median = (a) => { if (a.length < 5) return null; a.sort((p, q) => p - q); return a[a.length >> 1]; }; + for (let y = y0; y < y1; y++) { + const vs = []; let dk = 0, n = 0; + for (let x = x0; x < x1; x++) { + const i = 4 * (y * W + x), b = d[i + 2], c = x - x0; + n++; colN[c]++; + if (b < 0.5 * top) { dk++; colDark[c]++; continue; } + if (b < 0.7 * top) continue; + const span = b - zero[2]; + vs.push((d[i] - zero[0]) / span); + if ((y & 1) === 0) colVals[c].push((d[i + 1] - zero[1]) / span); + } + rows.push(median(vs)); rowDark.push(dk / n); + } + for (let c = 0; c < colVals.length; c++) { cols.push(median(colVals[c])); colDark[c] /= colN[c]; } + const fy = fitAxis(rows, rowDark), fx = fitAxis(cols, colDark); + if (!fx || !fy) return null; + const toImgY = (p) => fy.a + fy.s * (p - y0), toImgX = (p) => fx.a + fx.s * (p - x0); + const wf = [toImgX(wx), toImgY(wy), toImgX(wx + ww), toImgY(wy + wh)]; + return { + x: { a: fx.a - fx.s * x0, s: fx.s, lines: fx.lines }, y: { a: fy.a - fy.s * y0, s: fy.s, lines: fy.lines }, + window_frac: [Math.min(wf[0], wf[2]), Math.min(wf[1], wf[3]), Math.max(wf[0], wf[2]), Math.max(wf[1], wf[3])].map((v) => Math.round(v * 1000) / 1000), + confidence: fx.lines >= 2 && fy.lines >= 2 ? 'high' : fx.lines && fy.lines ? 'medium' : 'low', + }; + } + + // Moves a viewfinder found on the screenshot to where the app reads it in an injected image of W x H. + function mapViewfinder(vf, cal, W, H) { + const sx = cal.x.s * W, ax = cal.x.a * W, sy = cal.y.s * H, ay = cal.y.a * H; + const T = M(cv.matFromArray(2, 3, cv.CV_64F, [sx, 0, ax, 0, sy, ay])); + const mask = new cv.Mat(); + cv.warpAffine(vf.mask, mask, T, new cv.Size(W, H), cv.INTER_NEAREST, cv.BORDER_CONSTANT, new cv.Scalar(0)); + free(); + const hull = vf.hull.map((v, i) => Math.round(i % 2 ? ay + sy * v : ax + sx * v)); + const [x0, y0, x1, y1] = cal.window_frac; + return { result: { ...vf.result, calibrated: true, calibration: cal.confidence, window_px: [x0 * W, y0 * H, (x1 - x0) * W, (y1 - y0) * H].map(Math.round), window_frac: cal.window_frac }, + mask, hull }; + } + // ---------- subject in the image to inject ---------- let session = null; async function foregroundMask(rgba) { @@ -492,7 +661,18 @@ // shot, image: RGBA cv.Mat. Returns {output: RGBA cv.Mat (caller deletes), report} async function padfit(shot, image, opts = {}) { const fill = opts.fill ?? 0.92, rotate = opts.rotate ?? 0, cropMode = opts.crop ?? 'auto', pad = opts.pad ?? [128, 128, 128, 255]; - const vf = viewfinder(shot); + const screen = screenRect(shot); + let calib = opts.calib || null; + if (calib && (calib.cols !== shot.cols || calib.rows !== shot.rows)) throw new Error('The calibration screenshot must be the same size as the app screenshot'); + if (screen) { shot = shot.roi(new cv.Rect(...screen)); if (calib) calib = calib.roi(new cv.Rect(...screen)); } + let vf = viewfinder(shot), cal = null; + if (calib) { + cal = readCalibration(calib, vf.result.window_px); + if (screen) calib.delete(); + if (!cal) throw new Error('The calibration grid is not visible inside the viewfinder'); + const mapped = mapViewfinder(vf, cal, shot.cols, shot.rows); + vf.mask.delete(); vf = mapped; + } let img = image.clone(), subj = null, chosen = null; if (cropMode === 'auto') { const s = await subject(image); @@ -509,11 +689,12 @@ const small = new cv.Mat(); cv.resize(img, small, new cv.Size(w, h), 0, 0, cv.INTER_AREA); small.copyTo(out.roi(new cv.Rect(x0, y0, w, h))); small.delete(); img.delete(); vf.mask.delete(); - return { output: out, report: { ...vf.result, screenshot_size: [shot.cols, shot.rows], placed_px: [x0, y0, w, h], + if (screen) shot.delete(); + return { output: out, report: { ...vf.result, screen_crop_px: screen, screenshot_size: [out.cols, out.rows], placed_px: [x0, y0, w, h], scale: Math.round(s * 10000) / 10000, subject: subj, subject_box: chosen, rotated_deg: rotate } }; } - return { viewfinder, subject, cropTo, place, padfit, iou }; + return { screenRect, viewfinder, calibrationGrid, readCalibration, mapViewfinder, subject, cropTo, place, padfit, iou }; }); @@ -521,7 +702,7 @@ (() => { const $ = (id) => document.getElementById(id); const PAD = [128, 128, 128]; - const S = { cv: null, core: null, shot: null, img: null, vf: null, subj: null, cands: [], sel: 0, crop: null, + const S = { cv: null, core: null, shot: null, shotRaw: null, screen: null, calib: null, cal: null, vf0: null, img: null, vf: null, subj: null, cands: [], sel: 0, crop: null, rot90: 0, fine: 0, size: 0.92, cx: 0, cy: 0, base: 1, names: {}, mode: 'box', poly: null }; const setMsg = (t) => { $('msg').textContent = t || ''; }; @@ -561,7 +742,11 @@ try { c = await toCanvas(blob, kind === 'img' ? 2560 : 0); } catch { setMsg('That file is not an image this browser can read. Use PNG or JPEG.'); return; } const url = c.toDataURL('image/jpeg', 0.6); - if (kind === 'shot') { S.shot = c; $('thumbShot').src = url; $('nameShot').textContent = name; } + if (kind === 'shot') { S.shot = c; S.shotRaw = [c.width, c.height]; S.calib = null; $('thumbCal').removeAttribute('src'); $('nameCal').textContent = 'Grid visible in the viewfinder'; $('thumbShot').src = url; $('nameShot').textContent = name; } + else if (kind === 'calib') { + if (!S.shotRaw || c.width !== S.shotRaw[0] || c.height !== S.shotRaw[1]) { setMsg('The calibration screenshot must be the same size as the app screenshot. Take both on the same device.'); return; } + S.calib = c; $('thumbCal').src = url; $('nameCal').textContent = name; + } else { S.img = c; $('thumbImg').src = url; $('nameImg').textContent = name; } if (!isExample) $('exampleTag').hidden = true; setMsg(''); @@ -573,7 +758,7 @@ await setInput('shot', a, 'Example: test app, tint window', true); await setInput('img', b, 'Example: QR on a desk', true); } - for (const [k, drop, file] of [['shot', 'dropShot', 'fileShot'], ['img', 'dropImg', 'fileImg']]) { + for (const [k, drop, file] of [['shot', 'dropShot', 'fileShot'], ['img', 'dropImg', 'fileImg'], ['calib', 'dropCal', 'fileCal']]) { const d = $(drop), f = $(file); f.addEventListener('change', () => f.files[0] && setInput(k, f.files[0], f.files[0].name)); d.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); f.click(); } }); @@ -587,10 +772,21 @@ if (!S.core) return; const cv = S.cv; try { - if ((kind === 'shot' || !S.vf) && S.shot) { - if (S.vf) S.vf.mask.delete(); - const m = cv.imread(S.shot); S.vf = S.core.viewfinder(m); m.delete(); + if ((kind === 'shot' || !S.vf0) && S.shot) { + if (S.vf && S.vf !== S.vf0) S.vf.mask.delete(); + if (S.vf0) S.vf0.mask.delete(); + S.vf = S.vf0 = null; + const raw = cv.imread(S.shot); const screen = S.core.screenRect(raw); raw.delete(); + S.screen = screen; + if (screen) { + const [x, y, w, h] = screen, c = document.createElement('canvas'); c.width = w; c.height = h; + c.getContext('2d').drawImage(S.shot, x, y, w, h, 0, 0, w, h); + S.shot = c; $('thumbShot').src = c.toDataURL('image/jpeg', 0.6); + setMsg('Removed the phone frame around the screenshot. The output is the size of the screen inside it.'); + } + const m = cv.imread(S.shot); S.vf0 = S.vf = S.core.viewfinder(m); m.delete(); } + if (kind === 'shot' || kind === 'calib') applyCalibration(); if ((kind === 'img' || !S.subj) && S.img) { engine('Finding subject…'); const m = cv.imread(S.img); const s = await S.core.subject(m); m.delete(); @@ -610,6 +806,30 @@ } catch (e) { engine('Ready', true); setMsg('Analysis failed: ' + e.message); } renderAll(); } + function applyCalibration() { + const cv = S.cv; + if (S.vf && S.vf !== S.vf0) S.vf.mask.delete(); + S.vf = S.vf0; S.cal = null; + $('gridBtn').disabled = !S.shot; $('calClear').hidden = !S.calib; + if (!S.calib || !S.vf0) return; + const full = cv.imread(S.calib), m = S.screen ? full.roi(new cv.Rect(...S.screen)) : full; + const cal = S.core.readCalibration(m, S.vf0.result.window_px); + if (m !== full) m.delete(); full.delete(); + if (!cal) { setMsg('Could not find the grid inside the viewfinder. Check that the grid shows in the viewfinder (on Android, turn on Camera Preview).'); return; } + S.cal = cal; S.vf = S.core.mapViewfinder(S.vf0, cal, S.shot.width, S.shot.height); + const [, y0, , y1] = cal.window_frac; + setMsg(`Calibrated: the viewfinder shows ${Math.round(y0 * 100)}% to ${Math.round(y1 * 100)}% of the image height. The subject goes there.`); + } + $('gridBtn').addEventListener('click', () => { + if (!S.shot) return; + const g = S.core.calibrationGrid(S.shot.width, S.shot.height), c = document.createElement('canvas'); + S.cv.imshow(c, g); g.delete(); + c.toBlob((b) => { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = `padfit-calibration-grid_${c.width}x${c.height}.png`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); }, 'image/png'); + }); + $('calClear').addEventListener('click', () => { + S.calib = null; $('thumbCal').removeAttribute('src'); $('nameCal').textContent = 'Grid visible in the viewfinder'; + applyCalibration(); setMsg(''); if (S.crop) autoFit(); renderAll(); + }); const nice = (k) => ({ foreground: 'Foreground', saliency: 'Salient area', document: 'Document', manual: 'Your box', lasso: 'Your shape', whole: 'Whole image' }[k] || k); function buildChips() { @@ -684,8 +904,8 @@ ctx.save(); ctx.globalAlpha = alpha; ctx.translate(S.cx, S.cy); ctx.rotate(angle() * Math.PI / 180); ctx.imageSmoothingQuality = 'high'; ctx.drawImage(S.crop, -w / 2, -h / 2, w, h); ctx.restore(); } - function outline(ctx, lw) { - const h = S.vf.hull; if (!h || h.length < 6) return; + function outline(ctx, lw, vf = S.vf) { + const h = vf.hull; if (!h || h.length < 6) return; ctx.save(); ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue('--guide').trim() || '#19c25c'; ctx.lineWidth = lw; ctx.beginPath(); ctx.moveTo(h[0], h[1]); for (let i = 2; i < h.length; i += 2) ctx.lineTo(h[i], h[i + 1]); @@ -701,7 +921,7 @@ const cs = $('cShot'), ci = $('cImg'), co = $('cOut'), cc = $('cCheck'); if (S.shot) { cs.width = S.shot.width; cs.height = S.shot.height; const x = cs.getContext('2d'); x.drawImage(S.shot, 0, 0); - if (S.vf) outline(x, lw(cs)); + if (S.vf0) outline(x, lw(cs), S.vf0); } if (S.img) { ci.width = S.img.width; ci.height = S.img.height; const x = ci.getContext('2d'); x.drawImage(S.img, 0, 0); @@ -721,6 +941,7 @@ x.drawImage(S.shot, 0, 0); drawSubject(x, 0.85); outline(x, lw(cc)); $('save').disabled = false; } + $('checkNote').textContent = S.cal ? 'Calibrated: the subject sits where the app reads the image, so it can sit outside the box here. Drag to move' : 'Output over the screenshot. Drag to move'; status(); } function status() { @@ -729,6 +950,7 @@ if (S.vf) { const r = S.vf.result, ok = r.confidence >= 0.6; pill(`viewfinder: ${r.mode} · ${r.shape} · confidence ${r.confidence.toFixed(2)}`, ok ? 'ok' : 'warn'); + if (S.cal) pill(`calibrated: image ${Math.round(S.cal.window_frac[1] * 100)}–${Math.round(S.cal.window_frac[3] * 100)}% high · ${S.cal.confidence}`, S.cal.confidence === 'low' ? 'warn' : 'ok'); if (!ok) pill('Low confidence: check the green line, or use the two-gradient method', 'warn'); } if (S.subj) { From 7b6835fbff8448ab1f84181a169566805bbc1d95 Mon Sep 17 00:00:00 2001 From: Harshit Shah Date: Thu, 3 Dec 2026 19:43:39 +0530 Subject: [PATCH 2/2] feat(image-padding): two-input flow with calibration by default Rename PadFit to Image Padding Tool and make calibration the default flow. The tool now takes two inputs: the app screenshot and the image to inject. If the screenshot shows the injected calibration grid, the tool reads it and places the subject where the app reads the camera image. If it does not, the tool falls back to the viewfinder on screen. The calibration grid is now a fixed 1080x1920 image, so one download works for every app, and a calibrated output has that size. Layout: a single page with no scrolling. A step-by-step guide sits on the left. The screenshot, image and output panels are upload targets. The output panel is where the user checks the result and moves or resizes the image. Co-Authored-By: Claude Opus 5.5 --- docs/tools/image-padding/index.html | 621 +++++++++++++++++----------- 1 file changed, 372 insertions(+), 249 deletions(-) diff --git a/docs/tools/image-padding/index.html b/docs/tools/image-padding/index.html index 5f0023d..71221c1 100644 --- a/docs/tools/image-padding/index.html +++ b/docs/tools/image-padding/index.html @@ -1,16 +1,17 @@ -PadFit +Image Padding Tool -
-
- -
Loading engine…
-
-
- - -
-
-
-
1 · ScreenshotGreen line = viewfinder found
-
2 · Image to injectGreen line = subject. Drag to draw. Drag inside your shape to move it, scroll to resize
-
3 · OutputSame size as the screenshot. Grey = padding
-
4 · CheckOutput over the screenshot. Drag to move
-
-
-
-
+
    +
    The padded image shows here after both uploads.
    +
    ✥ Drag to move · Scroll to resize
    + + @@ -702,10 +776,11 @@ (() => { const $ = (id) => document.getElementById(id); const PAD = [128, 128, 128]; - const S = { cv: null, core: null, shot: null, shotRaw: null, screen: null, calib: null, cal: null, vf0: null, img: null, vf: null, subj: null, cands: [], sel: 0, crop: null, - rot90: 0, fine: 0, size: 0.92, cx: 0, cy: 0, base: 1, names: {}, mode: 'box', poly: null }; + const S = { cv: null, core: null, shot: null, screen: null, cal: null, vf0: null, img: null, imgName: '', vf: null, subj: null, cands: [], sel: 0, crop: null, + rot90: 0, fine: 0, size: 0.92, cx: 0, cy: 0, base: 1, mode: 'box', poly: null }; - const setMsg = (t) => { $('msg').textContent = t || ''; }; + let note = ''; + const setMsg = (t) => { note = t || ''; status(); }; const engine = (t, ok) => { $('engineText').textContent = t; $('engine').classList.toggle('ready', !!ok); }; function loadScript(src) { @@ -725,7 +800,7 @@ const b64 = (await (await fetch('u2netp.onnx.b64.txt')).text()).trim(); const bin = atob(b64); const model = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) model[i] = bin.charCodeAt(i); S.cv = cv; S.core = PadFitCore(cv, ort, model); engine('Ready', true); - await loadExample(); + if (S.shot || S.img) await analyse(S.img ? 'img' : 'shot'); } catch (e) { engine('Engine failed'); setMsg(e.message + '. Reload the page to try again.'); } } @@ -737,62 +812,69 @@ c.getContext('2d').drawImage(bmp, 0, 0, c.width, c.height); bmp.close && bmp.close(); return c; } - async function setInput(kind, blob, name, isExample) { + async function setInput(kind, blob, name) { let c; try { c = await toCanvas(blob, kind === 'img' ? 2560 : 0); } catch { setMsg('That file is not an image this browser can read. Use PNG or JPEG.'); return; } - const url = c.toDataURL('image/jpeg', 0.6); - if (kind === 'shot') { S.shot = c; S.shotRaw = [c.width, c.height]; S.calib = null; $('thumbCal').removeAttribute('src'); $('nameCal').textContent = 'Grid visible in the viewfinder'; $('thumbShot').src = url; $('nameShot').textContent = name; } - else if (kind === 'calib') { - if (!S.shotRaw || c.width !== S.shotRaw[0] || c.height !== S.shotRaw[1]) { setMsg('The calibration screenshot must be the same size as the app screenshot. Take both on the same device.'); return; } - S.calib = c; $('thumbCal').src = url; $('nameCal').textContent = name; - } - else { S.img = c; $('thumbImg').src = url; $('nameImg').textContent = name; } - if (!isExample) $('exampleTag').hidden = true; + if (kind === 'shot') { S.shot = c; $('wellShot').classList.add('has'); $('wellShot').setAttribute('aria-label', 'Change app screenshot'); } + else { S.img = c; S.imgName = name; S.subj = null; $('wellImg').classList.add('has'); $('changeImg').hidden = false; } + saved = false; setMsg(''); await analyse(kind); } - async function loadExample() { + $('example').addEventListener('click', async () => { const [a, b] = await Promise.all(['example-screen.png', 'example-image.png'].map(async (f) => (await fetch(f)).blob())); - $('exampleTag').hidden = false; - await setInput('shot', a, 'Example: test app, tint window', true); - await setInput('img', b, 'Example: QR on a desk', true); - } - for (const [k, drop, file] of [['shot', 'dropShot', 'fileShot'], ['img', 'dropImg', 'fileImg'], ['calib', 'dropCal', 'fileCal']]) { - const d = $(drop), f = $(file); - f.addEventListener('change', () => f.files[0] && setInput(k, f.files[0], f.files[0].name)); + await setInput('shot', a, 'example screen'); + await setInput('img', b, 'example-qr'); + setMsg('Example loaded: a normal screenshot of a test app and a QR code on a desk.'); + }); + for (const [k, well, file] of [['shot', 'wellShot', 'fileShot'], ['img', 'wellImg', 'fileImg']]) { + const d = $(well), f = $(file); + f.addEventListener('change', () => { if (f.files[0]) setInput(k, f.files[0], f.files[0].name); f.value = ''; }); + d.addEventListener('click', () => { if (k === 'shot' || !S.img) f.click(); }); d.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); f.click(); } }); d.addEventListener('dragover', (e) => { e.preventDefault(); d.classList.add('over'); }); d.addEventListener('dragleave', () => d.classList.remove('over')); d.addEventListener('drop', (e) => { e.preventDefault(); d.classList.remove('over'); const x = e.dataTransfer.files[0]; if (x) setInput(k, x, x.name); }); } + $('changeImg').addEventListener('click', () => $('fileImg').click()); // ---------- analysis ---------- + const outSize = () => (S.cal ? S.core.GRID_SIZE : [S.shot.width, S.shot.height]); + function dropViewfinder() { + if (S.vf && S.vf !== S.vf0) S.vf.mask.delete(); + if (S.vf0) S.vf0.mask.delete(); + S.vf = S.vf0 = null; S.cal = null; + } async function analyse(kind) { if (!S.core) return; const cv = S.cv; try { - if ((kind === 'shot' || !S.vf0) && S.shot) { - if (S.vf && S.vf !== S.vf0) S.vf.mask.delete(); - if (S.vf0) S.vf0.mask.delete(); - S.vf = S.vf0 = null; + if (kind === 'shot' && S.shot) { + dropViewfinder(); const raw = cv.imread(S.shot); const screen = S.core.screenRect(raw); raw.delete(); S.screen = screen; + const notes = []; if (screen) { const [x, y, w, h] = screen, c = document.createElement('canvas'); c.width = w; c.height = h; c.getContext('2d').drawImage(S.shot, x, y, w, h, 0, 0, w, h); - S.shot = c; $('thumbShot').src = c.toDataURL('image/jpeg', 0.6); - setMsg('Removed the phone frame around the screenshot. The output is the size of the screen inside it.'); + S.shot = c; notes.push('Removed the phone frame around the screenshot.'); } - const m = cv.imread(S.shot); S.vf0 = S.vf = S.core.viewfinder(m); m.delete(); + const m = cv.imread(S.shot); const a = S.core.analyseShot(m); m.delete(); + S.vf0 = a.vf; S.cal = a.cal; + if (S.cal) { + const [GW, GH] = S.core.GRID_SIZE; + S.vf = S.core.mapViewfinder(S.vf0, S.cal, GW, GH); + const [, y0, , y1] = S.cal.window_frac; + notes.push(`Calibration image found: the viewfinder shows ${Math.round(y0 * 100)}% to ${Math.round(y1 * 100)}% of the image height. The output puts the subject there.`); + } else S.vf = S.vf0; + setMsg(notes.join(' ')); } - if (kind === 'shot' || kind === 'calib') applyCalibration(); - if ((kind === 'img' || !S.subj) && S.img) { + if (kind === 'img' && S.img) { engine('Finding subject…'); const m = cv.imread(S.img); const s = await S.core.subject(m); m.delete(); engine('Ready', true); S.subj = s; - const W = S.img.width, H = S.img.height; const seen = []; S.cands = []; const add = (b, label) => { if (seen.some((x) => S.core.iou(x, b) > 0.9)) return; seen.push(b); S.cands.push({ b, label }); }; if (s.chosen) add(s.chosen, 'Auto · ' + nice(s.chosen.kind)); @@ -802,34 +884,48 @@ buildChips(); makeCrop(); S.rot90 = 0; S.fine = 0; S.size = 0.92; syncControls(); } - if (S.shot && S.img) autoFit(); + if (S.vf && S.crop) autoFit(); } catch (e) { engine('Ready', true); setMsg('Analysis failed: ' + e.message); } renderAll(); } - function applyCalibration() { - const cv = S.cv; - if (S.vf && S.vf !== S.vf0) S.vf.mask.delete(); - S.vf = S.vf0; S.cal = null; - $('gridBtn').disabled = !S.shot; $('calClear').hidden = !S.calib; - if (!S.calib || !S.vf0) return; - const full = cv.imread(S.calib), m = S.screen ? full.roi(new cv.Rect(...S.screen)) : full; - const cal = S.core.readCalibration(m, S.vf0.result.window_px); - if (m !== full) m.delete(); full.delete(); - if (!cal) { setMsg('Could not find the grid inside the viewfinder. Check that the grid shows in the viewfinder (on Android, turn on Camera Preview).'); return; } - S.cal = cal; S.vf = S.core.mapViewfinder(S.vf0, cal, S.shot.width, S.shot.height); - const [, y0, , y1] = cal.window_frac; - setMsg(`Calibrated: the viewfinder shows ${Math.round(y0 * 100)}% to ${Math.round(y1 * 100)}% of the image height. The subject goes there.`); + // Inside a claude.ai artifact a link download is blocked, so use its downloads capability there. + async function saveBlob(blob, filename) { + const dl = window.claude && window.claude.use ? await window.claude.use('downloads') : null; + if (dl) { await dl.save({ filename, data: blob }); return; } + const url = URL.createObjectURL(blob), a = document.createElement('a'); + a.href = url; a.download = filename; a.style.display = 'none'; + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 10000); } - $('gridBtn').addEventListener('click', () => { - if (!S.shot) return; - const g = S.core.calibrationGrid(S.shot.width, S.shot.height), c = document.createElement('canvas'); - S.cv.imshow(c, g); g.delete(); - c.toBlob((b) => { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = `padfit-calibration-grid_${c.width}x${c.height}.png`; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); }, 'image/png'); - }); - $('calClear').addEventListener('click', () => { - S.calib = null; $('thumbCal').removeAttribute('src'); $('nameCal').textContent = 'Grid visible in the viewfinder'; - applyCalibration(); setMsg(''); if (S.crop) autoFit(); renderAll(); - }); + const GRID_SIZE = [1080, 1920], GRID_STEP = 0.1; + // Same pixels as core.calibrationGrid, drawn without OpenCV so it works before the engine loads. + function calibrationGrid() { + const [W, H] = GRID_SIZE, c = document.createElement('canvas'); c.width = W; c.height = H; + const ctx = c.getContext('2d'), img = ctx.createImageData(W, H), d = img.data; + for (let y = 0; y < H; y++) { + const r = Math.round(255 * y / (H - 1)); + for (let x = 0; x < W; x++) { + const i = 4 * (y * W + x); + d[i] = r; d[i + 1] = Math.round(255 * x / (W - 1)); d[i + 2] = 255; d[i + 3] = 255; + } + } + ctx.putImageData(img, 0, 0); + const lw = Math.max(4, Math.round(0.012 * Math.min(W, H))), half = Math.floor(lw / 2), font = Math.min(W, H) / 900; + ctx.fillStyle = '#000'; ctx.font = `${Math.round(28 * font)}px Arial, sans-serif`; + for (let k = 1; k * GRID_STEP < 1 - 1e-9; k++) { + const y = Math.round(k * GRID_STEP * H), x = Math.round(k * GRID_STEP * W); + ctx.fillRect(0, y - half, W, lw); ctx.fillRect(x - half, 0, lw, H); + for (const lx of [0.02, 0.52]) ctx.fillText(`${k * 10}%`, Math.round(lx * W), y - 2 * lw); + } + return c; + } + const downloadGrid = () => { + gridSaved = true; steps(); + const c = calibrationGrid(); + c.toBlob((b) => saveBlob(b, `image-padding-calibration_${c.width}x${c.height}.png`).catch((e) => setMsg(e && e.code === 'declined' ? '' : 'Download failed: ' + (e && e.message || e))), 'image/png'); + }; + $('gridBtn').addEventListener('click', downloadGrid); $('gridAgain').addEventListener('click', downloadGrid); + $('haveShot').addEventListener('click', () => { shotTaken = true; steps(); }); const nice = (k) => ({ foreground: 'Foreground', saliency: 'Salient area', document: 'Document', manual: 'Your box', lasso: 'Your shape', whole: 'Whole image' }[k] || k); function buildChips() { @@ -855,15 +951,13 @@ ctx.drawImage(S.img, -x0, -y0); S.crop = cnv; return; } const m = cv.imread(S.img); - let out; - if (c.kind === 'whole') out = m.clone(); - else out = S.core.cropTo(m, c, c.kind === 'manual' ? 0 : 0.05); + const out = c.kind === 'whole' ? m.clone() : S.core.cropTo(m, c, c.kind === 'manual' ? 0 : 0.05); const cnv = document.createElement('canvas'); cv.imshow(cnv, out); m.delete(); out.delete(); S.crop = cnv; } - // ---------- placement ---------- + // ---------- placement (all in output pixels) ---------- const angle = () => S.rot90 * 90 + S.fine; function bbox(w, h, deg) { const a = deg * Math.PI / 180, c = Math.abs(Math.cos(a)), s = Math.abs(Math.sin(a)); return [w * c + h * s, w * s + h * c]; } function autoFit() { @@ -897,29 +991,47 @@ } return true; } + // Screenshot pixels per output pixel. With calibration the app shows image fraction a + s * p at screen pixel p. + function screenFromOutput() { + if (!S.cal) return { kx: 1, ky: 1, ox: 0, oy: 0 }; + const [W, H] = outSize(), c = S.cal; + return { kx: 1 / (c.x.s * W), ky: 1 / (c.y.s * H), ox: -c.x.a / c.x.s, oy: -c.y.a / c.y.s }; + } // ---------- rendering ---------- + const guide = () => getComputedStyle(document.documentElement).getPropertyValue('--guide').trim() || '#19c25c'; function drawSubject(ctx, alpha) { const w = S.crop.width * S.base * S.size, h = S.crop.height * S.base * S.size; ctx.save(); ctx.globalAlpha = alpha; ctx.translate(S.cx, S.cy); ctx.rotate(angle() * Math.PI / 180); ctx.imageSmoothingQuality = 'high'; ctx.drawImage(S.crop, -w / 2, -h / 2, w, h); ctx.restore(); } - function outline(ctx, lw, vf = S.vf) { + function hullPath(ctx, h) { ctx.beginPath(); ctx.moveTo(h[0], h[1]); for (let i = 2; i < h.length; i += 2) ctx.lineTo(h[i], h[i + 1]); ctx.closePath(); } + function outline(ctx, lw, vf) { const h = vf.hull; if (!h || h.length < 6) return; - ctx.save(); ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue('--guide').trim() || '#19c25c'; - ctx.lineWidth = lw; ctx.beginPath(); ctx.moveTo(h[0], h[1]); - for (let i = 2; i < h.length; i += 2) ctx.lineTo(h[i], h[i + 1]); - ctx.closePath(); ctx.stroke(); ctx.restore(); + ctx.save(); ctx.strokeStyle = guide(); ctx.lineWidth = lw; hullPath(ctx, h); ctx.stroke(); ctx.restore(); } function renderOutput(c) { - c.width = S.shot.width; c.height = S.shot.height; + [c.width, c.height] = outSize(); const ctx = c.getContext('2d'); ctx.fillStyle = `rgb(${PAD.join(',')})`; ctx.fillRect(0, 0, c.width, c.height); if (S.crop) drawSubject(ctx, 1); } + // The check view shows the subject the way the app shows it: dim outside the viewfinder, clear inside it. + function renderCheck(c, lw) { + c.width = S.shot.width; c.height = S.shot.height; const x = c.getContext('2d'); + x.drawImage(S.shot, 0, 0); + const t = screenFromOutput(), toScreen = () => x.setTransform(t.kx, 0, 0, t.ky, t.ox, t.oy); + x.save(); toScreen(); drawSubject(x, 0.3); x.restore(); + const h = S.vf0.hull; + if (h && h.length >= 6) { x.save(); hullPath(x, h); x.clip(); toScreen(); drawSubject(x, 0.95); x.restore(); } + outline(x, lw, S.vf0); + } function renderAll() { const lw = (c) => Math.max(3, c.width / 150); - const cs = $('cShot'), ci = $('cImg'), co = $('cOut'), cc = $('cCheck'); - if (S.shot) { + const cs = $('cShot'), ci = $('cImg'), co = $('cOut'); + const ready = !!(S.shot && S.crop && S.vf); + sizeShot(); + if (S.shot && ready) renderCheck(cs, lw(cs)); + else if (S.shot) { cs.width = S.shot.width; cs.height = S.shot.height; const x = cs.getContext('2d'); x.drawImage(S.shot, 0, 0); if (S.vf0) outline(x, lw(cs), S.vf0); } @@ -927,7 +1039,7 @@ ci.width = S.img.width; ci.height = S.img.height; const x = ci.getContext('2d'); x.drawImage(S.img, 0, 0); const b = S.cands[S.sel] && S.cands[S.sel].b; if (b && b.kind !== 'whole') { - x.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue('--guide').trim(); x.lineWidth = lw(ci); + x.strokeStyle = guide(); x.lineWidth = lw(ci); if (b.pts) { x.beginPath(); b.pts.forEach(([px, py], i) => (i ? x.lineTo(px * ci.width, py * ci.height) : x.moveTo(px * ci.width, py * ci.height))); x.closePath(); x.stroke(); } else if (b.corners) { x.beginPath(); b.corners.forEach(([px, py], i) => (i ? x.lineTo(px, py) : x.moveTo(px, py))); x.closePath(); x.stroke(); } else x.strokeRect(b.x * ci.width, b.y * ci.height, b.w * ci.width, b.h * ci.height); @@ -935,40 +1047,46 @@ if (drawPath && drawPath.length > 1) { x.setLineDash([lw(ci) * 3, lw(ci) * 2]); x.strokeStyle = '#ffb000'; x.lineWidth = lw(ci); x.beginPath(); drawPath.forEach(([px, py], i) => (i ? x.lineTo(px, py) : x.moveTo(px, py))); x.stroke(); x.setLineDash([]); } if (drawBox) { x.setLineDash([lw(ci) * 3, lw(ci) * 2]); x.strokeStyle = '#ffb000'; x.lineWidth = lw(ci); if (S.mode === 'oval') { x.beginPath(); x.ellipse(drawBox.x + drawBox.w / 2, drawBox.y + drawBox.h / 2, drawBox.w / 2, drawBox.h / 2, 0, 0, 2 * Math.PI); x.stroke(); } else x.strokeRect(drawBox.x, drawBox.y, drawBox.w, drawBox.h); x.setLineDash([]); } } - if (S.shot && S.crop && S.vf) { - renderOutput(co); - cc.width = S.shot.width; cc.height = S.shot.height; const x = cc.getContext('2d'); - x.drawImage(S.shot, 0, 0); drawSubject(x, 0.85); outline(x, lw(cc)); - $('save').disabled = false; - } - $('checkNote').textContent = S.cal ? 'Calibrated: the subject sits where the app reads the image, so it can sit outside the box here. Drag to move' : 'Output over the screenshot. Drag to move'; + $('wellOut').classList.toggle('has', ready); $('save').disabled = !ready; + if (ready) { renderOutput(co); outline(co.getContext('2d'), lw(co), S.vf); } + $('outNote').textContent = (S.cal ? 'The file to inject. Green line = where the app reads the image' : 'The file to inject. Green line = the viewfinder') + (ready ? ` · ${outSize().join(' × ')} px` : ''); + steps(); status(); } + let gridSaved = false, shotTaken = false, saved = false; + function steps() { + const plain = !!S.shot && !S.cal; + const done = [gridSaved || !!S.cal, shotTaken || !!S.cal, !!S.shot, !!S.img, saved]; + const skipped = [plain && !gridSaved, plain, false, false, false]; + let active = done.findIndex((d, i) => !d && !skipped[i]); + done.forEach((d, i) => { const el = $('step' + (i + 1)); el.classList.toggle('done', d && !skipped[i]); el.classList.toggle('skipped', skipped[i]); el.classList.toggle('active', i === active); }); + $('wellShot').classList.toggle('next', active === 2); $('wellImg').classList.toggle('next', active === 3); + } + document.querySelectorAll('.step b').forEach((b) => { + const open = () => b.parentElement.classList.toggle('open'); + b.addEventListener('click', open); + b.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); } }); + }); function status() { - const el = $('status'); el.textContent = ''; - const pill = (t, cls) => { const s = document.createElement('span'); s.className = 'pill ' + (cls || ''); s.textContent = t; el.appendChild(s); }; - if (S.vf) { - const r = S.vf.result, ok = r.confidence >= 0.6; - pill(`viewfinder: ${r.mode} · ${r.shape} · confidence ${r.confidence.toFixed(2)}`, ok ? 'ok' : 'warn'); - if (S.cal) pill(`calibrated: image ${Math.round(S.cal.window_frac[1] * 100)}–${Math.round(S.cal.window_frac[3] * 100)}% high · ${S.cal.confidence}`, S.cal.confidence === 'low' ? 'warn' : 'ok'); - if (!ok) pill('Low confidence: check the green line, or use the two-gradient method', 'warn'); - } - if (S.subj) { - const s = S.subj.sure; - pill(`subject: ${S.subj.chosen ? nice(S.subj.chosen.kind) : 'none'} · confidence ${(s.confidence || 0).toFixed(2)}`, s.verdict === 'sure' ? 'ok' : 'warn'); - } - if (S.vf && S.crop) { - const inside = insideViewfinder(); - pill(inside ? 'subject inside the viewfinder' : 'subject goes outside the viewfinder', inside ? 'ok' : 'warn'); - pill(`output ${S.shot.width} × ${S.shot.height}`); + const list = (id) => { const el = $(id); el.textContent = ''; return (t, cls) => { const li = document.createElement('li'); if (cls) li.className = cls; li.textContent = t; el.appendChild(li); }; }; + const shot = list('statusShot'), img = list('statusImg'), out = list('status'); + if (S.vf0) { + if (S.cal) shot(`Calibrated: the app reads ${Math.round(S.cal.window_frac[1] * 100)}–${Math.round(S.cal.window_frac[3] * 100)}% of the image height`, 'ok'); + else shot('Not calibrated: the image goes in the viewfinder on screen'); + if (S.vf0.result.confidence < 0.6) shot('Viewfinder unsure: check the green line', 'warn'); } + if (S.subj && S.subj.sure.verdict !== 'sure') img('Subject unsure: draw a box around it', 'warn'); + if (S.vf && S.crop) out(insideViewfinder() ? 'Subject is inside the green line' : 'Subject goes outside the green line: make it smaller or move it', insideViewfinder() ? 'ok' : 'warn'); + if (note) out(note); + $('imgTools').setAttribute('aria-disabled', String(!S.img)); + $('outTools').setAttribute('aria-disabled', String(!(S.vf && S.crop))); } // ---------- controls ---------- function syncControls() { $('angleVal').textContent = `${(((angle() % 360) + 360) % 360).toFixed(1).replace(/\.0$/, '')}°`; $('fine').value = S.fine; $('size').value = Math.round(S.size * 100); - $('sizeVal').textContent = `${Math.round(S.size * 100)}% of largest fit`; + $('sizeVal').textContent = `${Math.round(S.size * 100)}%`; } const refit = () => { autoFit(); syncControls(); renderAll(); }; $('rotL').addEventListener('click', () => { S.rot90 = (S.rot90 + 3) % 4; refit(); }); @@ -985,16 +1103,16 @@ const toCanvasXY = (c, e) => { const r = c.getBoundingClientRect(); return [(e.clientX - r.left) * c.width / r.width, (e.clientY - r.top) * c.height / r.height]; }; - // move + resize on the check view + // move + resize on the output view let drag = null; - const cc = $('cCheck'); - cc.addEventListener('pointerdown', (e) => { if (!S.crop) return; const [x, y] = toCanvasXY(cc, e); drag = { x, y, cx: S.cx, cy: S.cy }; cc.setPointerCapture(e.pointerId); cc.classList.add('dragging'); }); + const cc = $('cOut'); + cc.addEventListener('pointerdown', (e) => { if (!S.crop || !S.vf) return; const [x, y] = toCanvasXY(cc, e); drag = { x, y, cx: S.cx, cy: S.cy }; cc.setPointerCapture(e.pointerId); cc.classList.add('dragging'); }); cc.addEventListener('pointermove', (e) => { if (!drag) return; const [x, y] = toCanvasXY(cc, e); S.cx = drag.cx + x - drag.x; S.cy = drag.cy + y - drag.y; requestAnimationFrame(renderAll); }); const endDrag = () => { drag = null; cc.classList.remove('dragging'); }; cc.addEventListener('pointerup', endDrag); cc.addEventListener('pointercancel', endDrag); cc.addEventListener('wheel', (e) => { if (!S.crop) return; e.preventDefault(); S.size = Math.min(1.5, Math.max(0.1, S.size * (e.deltaY < 0 ? 1.04 : 1 / 1.04))); syncControls(); renderAll(); }, { passive: false }); - // move or resize the drawn subject on the image view + // move or resize the marked subject on the image view const ci = $('cImg'); const selPts = (b) => b.pts || [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]]; const editable = () => { const b = S.cands[S.sel] && S.cands[S.sel].b; return b && (b.kind === 'manual' || b.kind === 'lasso') ? b : null; }; @@ -1043,7 +1161,7 @@ clearTimeout(selTimer); selTimer = setTimeout(commitSel, 150); }, { passive: false }); - // draw a subject box or free shape on the image view + // mark a subject box, oval or free shape on the image view let drawBox = null, drawStart = null, drawPath = null; const setMode = (m) => { S.mode = m; $('modeBox').setAttribute('aria-pressed', String(m === 'box')); $('modeOval').setAttribute('aria-pressed', String(m === 'oval')); $('modeFree').setAttribute('aria-pressed', String(m === 'free')); }; $('modeOval').addEventListener('click', () => setMode('oval')); @@ -1095,21 +1213,26 @@ $('save').addEventListener('click', async () => { const c = document.createElement('canvas'); renderOutput(c); const blob = await new Promise((r) => c.toBlob(r, 'image/png')); - const base = (S.img && $('nameImg').textContent.replace(/^Example: /, '').replace(/\.[a-z0-9]+$/i, '').replace(/[^\w-]+/g, '_')) || 'image'; if (!blob) { setMsg('Save failed: could not create the PNG.'); return; } - const filename = `padfit_${base}_${c.width}x${c.height}.png`; - try { - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); a.href = url; a.download = filename; a.style.display = 'none'; - document.body.appendChild(a); a.click(); a.remove(); - setTimeout(() => URL.revokeObjectURL(url), 10000); - setMsg('Saved ' + filename); - } catch (e) { setMsg('Save failed: ' + (e && e.message || e)); } + const base = (S.imgName || 'image').replace(/\.[a-z0-9]+$/i, '').replace(/[^\w-]+/g, '_'); + const filename = `padded_${base}_${c.width}x${c.height}.png`; + try { await saveBlob(blob, filename); saved = true; steps(); setMsg('Saved ' + filename); } + catch (e) { setMsg(e && e.code === 'declined' ? '' : 'Save failed: ' + (e && e.message || e)); } }); + // The screenshot panel takes the phone's shape: its width follows its height. + function sizeShot() { + const w = $('wellShot'); + if (innerWidth <= 1100) { w.style.width = ''; return; } + const ar = S.shot ? S.shot.width / S.shot.height : 9 / 19.5; + w.style.width = Math.round(Math.min(360, Math.max(150, w.clientHeight * ar))) + 'px'; + } + addEventListener('resize', sizeShot); + syncControls(); + sizeShot(); boot(); })(); - \ No newline at end of file +