import path from "node:path"; import sharp from "sharp"; import type { TextEditRegion } from "./text-edit-region"; type Point = { x: number; y: number }; type Pixel = [number, number, number, number]; type Raster = { data: Buffer; width: number; height: number; }; type TextLine = { center: Point; width: number; height: number; angle: number; }; type Edit = { originalText: string; editedText: string; textColor?: string; region: TextEditRegion; }; export class LocalTextEditError extends Error {} const FONT_FILE = path.resolve("public/fonts/smart-edit/source-han.otf"); const FONT_FAMILY = "Source Han Sans SC"; export async function editCanvasTextLocally( source: Buffer, edits: Edit[], maxPixels: number, ): Promise { const { data, info } = await sharp(source, { limitInputPixels: maxPixels }) .autoOrient() .toColourspace("srgb") .ensureAlpha() .raw() .toBuffer({ resolveWithObject: true }); const original = { data, width: info.width, height: info.height }; const output = { ...original, data: Buffer.from(original.data) }; const lines = edits.map((edit) => ({ ...edit, line: toTextLine(edit.region, original) })); const editArea = lines.reduce((area, { line }) => area + line.width * line.height, 0); if (editArea > 2_000_000) { throw new LocalTextEditError("所选文字区域较大,请分次编辑"); } const redraw = lines.map((edit) => { const recolor = edit.editedText === edit.originalText ? edit.textColor : undefined; const inkColor = updateTextInk(original, output, edit.line, edit.originalText, recolor); return { ...edit, color: edit.textColor || inkColor, recolor }; }); for (const edit of redraw) { if (edit.editedText && !edit.recolor) { await drawText(output, edit.line, edit.editedText, edit.color); } } return sharp(output.data, { raw: { width: output.width, height: output.height, channels: 4 }, }).png().toBuffer(); } function toTextLine(region: TextEditRegion, image: Raster): TextLine { const points = [0, 2, 4, 6].map((index) => ({ x: region[index] * image.width, y: region[index + 1] * image.height, })); const [topLeft, topRight, bottomRight, bottomLeft] = points; const dx = (topRight.x - topLeft.x + bottomRight.x - bottomLeft.x) / 2; const dy = (topRight.y - topLeft.y + bottomRight.y - bottomLeft.y) / 2; const width = Math.hypot(dx, dy); const height = ( Math.hypot(bottomLeft.x - topLeft.x, bottomLeft.y - topLeft.y) + Math.hypot(bottomRight.x - topRight.x, bottomRight.y - topRight.y) ) / 2; if (width < 2 || height < 2 || width * height > image.width * image.height / 3) { throw new LocalTextEditError("文字位置不够准确,请重新识别后再试"); } return { center: { x: points.reduce((sum, point) => sum + point.x, 0) / 4, y: points.reduce((sum, point) => sum + point.y, 0) / 4, }, width, height, angle: Math.atan2(dy, dx), }; } function getPixel(image: Raster, x: number, y: number): Pixel { const offset = (y * image.width + x) * 4; return [ image.data[offset], image.data[offset + 1], image.data[offset + 2], image.data[offset + 3], ]; } function absolutePoint(line: TextLine, u: number, v: number): Point { const cos = Math.cos(line.angle); const sin = Math.sin(line.angle); return { x: line.center.x + u * cos - v * sin, y: line.center.y + u * sin + v * cos, }; } function sampleEdge(image: Raster, line: TextLine, u: number, v: number, step: number) { const samples: Pixel[] = []; for (let i = 0; i < 3; i++) { const point = absolutePoint(line, u, v + i * step); const x = Math.floor(point.x); const y = Math.floor(point.y); if (x < 0 || x >= image.width || y < 0 || y >= image.height) continue; samples.push(getPixel(image, x, y)); } if (samples.length === 0) return; return medianPixel(samples); } function medianPixel(samples: Pixel[]): Pixel { return [0, 1, 2, 3].map((channel) => samples.map((sample) => sample[channel]).sort((a, b) => a - b)[samples.length >> 1], ) as Pixel; } function mixPixels(a: Pixel, b: Pixel, t: number): Pixel { return [0, 1, 2, 3].map((channel) => a[channel] + (b[channel] - a[channel]) * t ) as Pixel; } function pixelDifference(a: Pixel, b: Pixel): Pixel { return [0, 1, 2, 3].map((channel) => a[channel] - b[channel]) as Pixel; } function magnitude(pixel: Pixel) { return Math.hypot(...pixel); } function colorHex(pixel: Pixel) { return `#${pixel.slice(0, 3).map((value) => value.toString(16).padStart(2, "0")).join("")}`; } function updateTextInk(original: Raster, output: Raster, line: TextLine, text: string, recolor?: string) { const padding = Math.max(2, Math.min(6, Math.round(Math.min(line.width, line.height) * 0.08))); const halfWidth = line.width / 2 + padding; const halfHeight = line.height / 2 + padding; const corners = [ absolutePoint(line, -halfWidth, -halfHeight), absolutePoint(line, halfWidth, -halfHeight), absolutePoint(line, halfWidth, halfHeight), absolutePoint(line, -halfWidth, halfHeight), ]; const left = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.x)))); const top = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.y)))); const right = Math.min(original.width, Math.ceil(Math.max(...corners.map((point) => point.x)))); const bottom = Math.min(original.height, Math.ceil(Math.max(...corners.map((point) => point.y)))); const cos = Math.cos(line.angle); const sin = Math.sin(line.angle); // In a narrow line, samples from either side preserve detail that crosses the text band. const transpose = line.height > line.width * 1.7; const extent = transpose ? halfWidth : halfHeight; const referenceLine = transpose ? { ...line, angle: line.angle - Math.PI / 2 } : line; const samples = new Map(); function backgroundAt(u: number, v: number) { const alongLine = transpose ? -v : u; const lane = Math.floor(alongLine); let pair = samples.get(lane); if (!pair) { const before = sampleEdge(original, referenceLine, alongLine, -extent - 1, -1); const after = sampleEdge(original, referenceLine, alongLine, extent + 1, 1); const existing = before ?? after; if (!existing) return; pair = [before ?? existing, after ?? existing]; samples.set(lane, pair); } const across = transpose ? u : v; return mixPixels(pair[0], pair[1], (across / extent + 1) / 2); } const sampleInk: Array<{ pixel: Pixel; delta: Pixel; contrast: number }> = []; const width = right - left; const height = bottom - top; const sampleStep = Math.max(1, Math.round(Math.sqrt(width * height / 6000))); for (let y = top; y < bottom; y += sampleStep) { for (let x = left; x < right; x += sampleStep) { const dx = x + 0.5 - line.center.x; const dy = y + 0.5 - line.center.y; const u = dx * cos + dy * sin; const v = -dx * sin + dy * cos; if (Math.abs(u) > line.width / 2 || Math.abs(v) > line.height / 2) continue; const background = backgroundAt(u, v); if (!background) continue; const pixel = getPixel(original, x, y); const delta = pixelDifference(pixel, background); sampleInk.push({ pixel, delta, contrast: magnitude(delta) }); } } sampleInk.sort((a, b) => b.contrast - a.contrast); const strongest = sampleInk.slice(0, Math.max(3, Math.floor(sampleInk.length * 0.08))); const ink = strongest.length > 0 ? medianPixel(strongest.map((sample) => sample.pixel)) : undefined; const direction = strongest.length > 0 ? medianPixel(strongest.map((sample) => sample.delta)) : undefined; const contrast = direction ? magnitude(direction) : 0; if (!ink || !direction || contrast < 15) { throw new LocalTextEditError(`无法准确去除「${text.slice(0, 24)}」,请重新识别`); } const threshold = Math.max(8, Math.min(16, contrast * 0.08)); const mask = new Uint8Array(width * height); const colorRgb = recolor?.slice(1).match(/../g)?.map((channel) => Number.parseInt(channel, 16)); let foundInk = false; for (let y = top; y < bottom; y++) { for (let x = left; x < right; x++) { const dx = x + 0.5 - line.center.x; const dy = y + 0.5 - line.center.y; const u = dx * cos + dy * sin; const v = -dx * sin + dy * cos; if (Math.abs(u) > halfWidth || Math.abs(v) > halfHeight) continue; const background = backgroundAt(u, v); if (!background) continue; const delta = pixelDifference(getPixel(original, x, y), background); const alongInk = delta.reduce((dot, value, channel) => dot + value * direction[channel], 0) / contrast; if (alongInk <= threshold || alongInk < magnitude(delta) * 0.75) continue; foundInk = true; mask[(y - top) * width + x - left] = 1; if (colorRgb) { const coverage = Math.min(1, alongInk / contrast); const offset = (y * output.width + x) * 4; for (let channel = 0; channel < 3; channel++) { output.data[offset + channel] = Math.round( background[channel] + (colorRgb[channel] - background[channel]) * coverage, ); } } } } if (!foundInk) { throw new LocalTextEditError(`无法准确定位「${text.slice(0, 24)}」,请重新识别`); } if (colorRgb) return colorHex(ink); // Include antialiasing and compression around each stroke without filling the text box. const halo = Math.min(3, Math.max(2, Math.round(padding / 2))); for (let y = top; y < bottom; y++) { for (let x = left; x < right; x++) { const dx = x + 0.5 - line.center.x; const dy = y + 0.5 - line.center.y; const u = dx * cos + dy * sin; const v = -dx * sin + dy * cos; if (Math.abs(u) > halfWidth || Math.abs(v) > halfHeight) continue; if (!hasNearbyInk(mask, width, height, x - left, y - top, halo)) continue; const background = backgroundAt(u, v); if (!background) continue; const offset = (y * output.width + x) * 4; for (let channel = 0; channel < 4; channel++) { output.data[offset + channel] = Math.round(background[channel]); } } } return colorHex(ink); } function hasNearbyInk(mask: Uint8Array, width: number, height: number, x: number, y: number, halo: number) { for (let row = Math.max(0, y - halo); row <= Math.min(height - 1, y + halo); row++) { for (let col = Math.max(0, x - halo); col <= Math.min(width - 1, x + halo); col++) { if (mask[row * width + col]) return true; } } return false; } function escapeText(text: string) { return text.replace(/&/g, "&").replace(//g, ">"); } async function drawText(output: Raster, line: TextLine, text: string, color: string) { const vertical = line.height > line.width * 1.7 && /\p{Script=Han}/u.test(text); const width = Math.max(1, Math.floor(line.width)); const height = Math.max(1, Math.floor(line.height)); const glyphSize = vertical ? width : height; const pointSize = Math.max(1, Math.floor(glyphSize * 0.82)); const contents = vertical ? Array.from(text).join("\n") : text.replace(/\s+/g, " "); const layer = await sharp({ text: { text: `${escapeText(contents)}`, font: `${FONT_FAMILY} ${pointSize}`, fontfile: FONT_FILE, rgba: true, }, }).resize({ width, height, fit: "inside", withoutEnlargement: true }) .raw().toBuffer({ resolveWithObject: true }); const originX = vertical ? -layer.info.width / 2 : -line.width / 2; const originY = vertical ? -line.height / 2 : -layer.info.height / 2; const corners = [ absolutePoint(line, originX, originY), absolutePoint(line, originX + layer.info.width, originY), absolutePoint(line, originX + layer.info.width, originY + layer.info.height), absolutePoint(line, originX, originY + layer.info.height), ]; const left = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.x)))); const top = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.y)))); const right = Math.min(output.width, Math.ceil(Math.max(...corners.map((point) => point.x)))); const bottom = Math.min(output.height, Math.ceil(Math.max(...corners.map((point) => point.y)))); const cos = Math.cos(line.angle); const sin = Math.sin(line.angle); for (let y = top; y < bottom; y++) { for (let x = left; x < right; x++) { const dx = x + 0.5 - line.center.x; const dy = y + 0.5 - line.center.y; const u = Math.floor(dx * cos + dy * sin - originX); const v = Math.floor(-dx * sin + dy * cos - originY); if (u < 0 || u >= layer.info.width || v < 0 || v >= layer.info.height) continue; const src = (v * layer.info.width + u) * 4; const dst = (y * output.width + x) * 4; const alpha = layer.data[src + 3] / 255; if (alpha === 0) continue; const remaining = output.data[dst + 3] / 255 * (1 - alpha); const combined = alpha + remaining; for (let channel = 0; channel < 3; channel++) { output.data[dst + channel] = Math.round( (layer.data[src + channel] * alpha + output.data[dst + channel] * remaining) / combined, ); } output.data[dst + 3] = Math.round(combined * 255); } } }