From e1579eb3cf4b6a8d9c32b63a4bb49de374fb0d1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B4=AE=E7=94=9F=EF=BC=88=E5=AD=90=E8=99=9A=EF=BC=89?= <2234839456@qq.com> Date: Sun, 1 Nov 2026 18:45:50 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E6=89=BE=E5=AD=97?= =?UTF-8?q?=E4=BD=93=E9=A2=84=E8=A7=88=E9=95=82=E7=A9=BA=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/font_util/glyph_bitmap.ts | 39 +++++++++++++++++------------- package.json | 2 +- scripts/test_glyph_match.ts | 35 +++++++++++++++++++++++++++ src/font-finder/matcher.ts | 17 +++++++++++++ src/pages/FontFinder.vue | 40 +++++++++++-------------------- 5 files changed, 89 insertions(+), 44 deletions(-) diff --git a/backend/font_util/glyph_bitmap.ts b/backend/font_util/glyph_bitmap.ts index 96c2a3b..703201d 100644 --- a/backend/font_util/glyph_bitmap.ts +++ b/backend/font_util/glyph_bitmap.ts @@ -175,33 +175,38 @@ function flattenContour(rawContour: RawContour): Pt[] { } /** - * 扫描线填充多边形集合(奇偶规则),输出覆盖网格的二值位图 - * polys 顶点已是目标网格坐标系(含翻转与缩放) + * 扫描线按非零环绕规则填充多边形集合 + * polys 顶点已是目标网格坐标系(含翻转与缩放)。 + * 必须合并全部轮廓的交点:外轮廓与内轮廓方向相反,内轮廓处的环绕数归零, + * 从而保留「借」「日」等字形的封闭留白。 */ function scanlineFill(polys: Pt[][]): Uint8Array { const grid = new Uint8Array(GRID * GRID); - for (const poly of polys) { - if (poly.length < 3) continue; - for (let y = 0; y < GRID; y++) { - const sy = y + 0.5; - /** 收集该扫描线与全部边的交点 x */ - const xs: number[] = []; + for (let y = 0; y < GRID; y++) { + const sy = y + 0.5; + const crossings: Array<{ x: number; winding: number }> = []; + for (const poly of polys) { + if (poly.length < 3) continue; for (let i = 0; i < poly.length; i++) { const a = poly[i]!; const b = poly[(i + 1) % poly.length]!; - /** 水平边无交点 */ if (a.y === b.y) continue; if ((sy >= a.y && sy < b.y) || (sy >= b.y && sy < a.y)) { - xs.push(a.x + ((sy - a.y) / (b.y - a.y)) * (b.x - a.x)); + crossings.push({ + x: a.x + ((sy - a.y) / (b.y - a.y)) * (b.x - a.x), + winding: a.y < b.y ? 1 : -1, + }); } } - if (xs.length < 2) continue; - xs.sort((p, q) => p - q); - for (let k = 0; k + 1 < xs.length; k += 2) { - const x0 = Math.max(0, Math.ceil(xs[k]! - 0.5)); - const x1 = Math.min(GRID - 1, Math.floor(xs[k + 1]! - 0.5)); - for (let x = x0; x <= x1; x++) grid[y * GRID + x] = 1; - } + } + crossings.sort((a, b) => a.x - b.x); + let winding = 0; + for (let i = 0; i + 1 < crossings.length; i++) { + winding += crossings[i]!.winding; + if (winding === 0) continue; + const x0 = Math.max(0, Math.ceil(crossings[i]!.x - 0.5)); + const x1 = Math.min(GRID - 1, Math.floor(crossings[i + 1]!.x - 0.5)); + for (let x = x0; x <= x1; x++) grid[y * GRID + x] = 1; } } return grid; diff --git a/package.json b/package.json index 1964cc3..9b533ce 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "webfont", "private": true, - "version": "1.14.0", + "version": "1.14.1", "type": "module", "scripts": { "dev": "pnpx tsx scripts/dev-all.ts", diff --git a/scripts/test_glyph_match.ts b/scripts/test_glyph_match.ts index 1befeef..4f72648 100644 --- a/scripts/test_glyph_match.ts +++ b/scripts/test_glyph_match.ts @@ -18,6 +18,35 @@ import { fontDirs } from "../backend/config"; const TARGET_FONT = "思源黑体.ttf"; const TEXT = "天地玄黄"; +/** 统计不与位图边缘连通的白色像素,用于验证字形内部镂空仍然存在 */ +function countEnclosedWhitePixels(bitmap: Uint8Array): number { + const visited = new Uint8Array(bitmap.length); + let enclosedTotal = 0; + for (let start = 0; start < bitmap.length; start++) { + if (bitmap[start] || visited[start]) continue; + const stack = [start]; + visited[start] = 1; + let size = 0; + let enclosed = true; + while (stack.length) { + const index = stack.pop()!; + const x = index % 64; + const y = Math.floor(index / 64); + size++; + if (x === 0 || y === 0 || x === 63 || y === 63) enclosed = false; + const neighbors = [index - 1, index + 1, index - 64, index + 64]; + for (const next of neighbors) { + if (next < 0 || next >= bitmap.length || bitmap[next] || visited[next]) continue; + if ((x === 0 && next === index - 1) || (x === 63 && next === index + 1)) continue; + visited[next] = 1; + stack.push(next); + } + } + if (enclosed) enclosedTotal += size; + } + return enclosedTotal; +} + async function main() { console.log("=== 服务端字形比对自测 ==="); @@ -28,6 +57,12 @@ async function main() { }); if (!ttf) throw new Error(`无法加载目标字体 ${TARGET_FONT}`); + /** 「借」的「日」有两个封闭留白,不能因轮廓填充错误变成实心 */ + const jieBitmap = getGlyphBitmap(ttf, TARGET_FONT, "借".codePointAt(0)!); + const enclosed = jieBitmap ? countEnclosedWhitePixels(jieBitmap) : 0; + console.log(` 借: 封闭留白像素=${enclosed}`); + if (enclosed < 8) throw new Error(`${TARGET_FONT} 的「借」内部留白丢失`); + const queryBitmaps: Uint8Array[] = []; for (const ch of TEXT) { const cp = ch.codePointAt(0)!; diff --git a/src/font-finder/matcher.ts b/src/font-finder/matcher.ts index ff9b30a..8306dcc 100644 --- a/src/font-finder/matcher.ts +++ b/src/font-finder/matcher.ts @@ -130,6 +130,23 @@ async function loadSubsetFontFace(font: string, text: string): Promise return face; } +/** 一次裁剪指定字体所需字符,并用浏览器生成各字符的归一化预览 */ +export async function renderSubsetGlyphPreviews(font: string, chars: string[]): Promise> { + const face = await loadSubsetFontFace(font, [...new Set(chars)].join("")); + const previews = new Map(); + try { + for (const char of new Set(chars)) { + const rawMask = renderCharMask(char, face.family, 96); + if (rawMask) { + previews.set(char, rgbaToDataURL(maskToNormalizedRGBA(tightCrop(rawMask)))); + } + } + } finally { + document.fonts.delete(face); + } + return previews; +} + /** * 对单个候选字体执行比对 * diff --git a/src/pages/FontFinder.vue b/src/pages/FontFinder.vue index 2ab35af..d5861c4 100644 --- a/src/pages/FontFinder.vue +++ b/src/pages/FontFinder.vue @@ -10,8 +10,7 @@ */ import { ref, computed, useTemplateRef } from "vue"; import { usePageSeo } from "../useSeo"; -import { prepareQueryGlyphs } from "../font-finder/matcher"; -import { rgbaToDataURL } from "../font-finder/segmenter"; +import { prepareQueryGlyphs, renderSubsetGlyphPreviews } from "../font-finder/matcher"; /** 服务端返回的单字体结果(与 backend/routes/glyph_match.ts 对齐) */ interface ServerFontResult { @@ -28,19 +27,6 @@ function rgbaToBitString(rgba: Uint8Array): string { return s; } -/** 01 串 → 灰度预览 DataURL */ -function bitStringToDataURL(bits: string): string { - const rgba = new Uint8Array(64 * 64 * 4); - for (let i = 0; i < bits.length; i++) { - const v = bits[i] === "1" ? 0 : 255; - rgba[i * 4] = v; - rgba[i * 4 + 1] = v; - rgba[i * 4 + 2] = v; - rgba[i * 4 + 3] = 255; - } - return rgbaToDataURL(rgba); -} - usePageSeo({ title: "截图找字体 | 以图搜字体 | 在线字体识别", description: "上传文字截图,框选并确认文字,即可在站内字体库中查找字形最相似的字体。", @@ -226,16 +212,10 @@ function onGlyphInput() { results.value = []; } -/** 服务端结果 → 展示用预览图(同字体同字只转一次) */ +/** 裁剪接口生成的字体预览缓存(同字体同字只渲染一次) */ const glyphPreviewCache = new Map(); -function serverGlyphPreview(font: string, char: string, bitmap: string): string { - const key = font + "|" + char; - let url = glyphPreviewCache.get(key); - if (!url) { - url = bitStringToDataURL(bitmap); - glyphPreviewCache.set(key, url); - } - return url; +function serverGlyphPreview(font: string, char: string): string { + return glyphPreviewCache.get(font + "|" + char) ?? ""; } /** 结果中的查询序号 → 原始图块预览,留空图块与候选字体缺字均不会造成错位 */ @@ -266,7 +246,15 @@ async function startMatch() { if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = (await res.json()) as { results?: ServerFontResult[]; error?: string }; if (data.error) throw new Error(data.error); - results.value = data.results ?? []; + const matchedResults = data.results ?? []; + /** 每个字体只裁剪一次,同次裁剪包含该结果需要展示的全部字符 */ + await Promise.all(matchedResults.map(async (result) => { + const previews = await renderSubsetGlyphPreviews(result.font, result.glyphs.map((g) => g.char)); + for (const [char, preview] of previews) { + glyphPreviewCache.set(result.font + "|" + char, preview); + } + })); + results.value = matchedResults; totalCount.value = results.value.length; doneCount.value = results.value.length; elapsedMs.value = Math.round(performance.now() - t0); @@ -401,7 +389,7 @@ const scoreColor = (s: number) => (s > 0.9 ? "#16a34a" : s > 0.8 ? "#d97706" : "
- +
{{ g.char }} {{ pct(g.score) }}