import sharp from "sharp"; import path from "node:path"; const notoSansThaiFiles = path.join(process.cwd(), "node_modules", "@fontsource", "noto-sans-thai", "files"); const notoSansThaiSemiBold = path.join(notoSansThaiFiles, "noto-sans-thai-thai-600-normal.woff"); const notoSansThaiBold = path.join(notoSansThaiFiles, "noto-sans-thai-thai-700-normal.woff"); function escapeXml(value: string) { return value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!); } function headlineLines(value: string, max = 24): string[] { const words = value.trim().replace(/\s+/g, " ").split(" "); const lines: string[] = []; let line = ""; for (const word of words) { const candidate = line ? `${line} ${word}` : word; if (candidate.length > max && line) { lines.push(line); line = word; } else line = candidate; } if (line) lines.push(line); return lines.slice(0, 3); } /** Adds a reliable Thai editorial headline after image generation; image models do not typeset Thai safely. */ export async function addArticleHeadline(image: Buffer, headline: string, accent = "#0077B6"): Promise { const lines = headlineLines(headline); if (!lines.length) return image; const svg = ` `; const label = await sharp({ text: { text: "AI UPDATE", font: "Noto Sans Thai SemiBold 29px", fontfile: notoSansThaiSemiBold, rgba: true }, }).tint("#FFFFFF").png().toBuffer(); const headlineLayers = await Promise.all(lines.map((line) => sharp({ text: { text: escapeXml(line), font: "Noto Sans Thai Bold 64px", fontfile: notoSansThaiBold, rgba: true }, }).tint("#FFFFFF").png().toBuffer())); return sharp(image, { limitInputPixels: 40_000_000 }) .resize(1024, 1024, { fit: "cover" }) .composite([ { input: Buffer.from(svg) }, { input: label, left: 64, top: 620 }, ...headlineLayers.map((input, index) => ({ input, left: 64, top: 680 + index * 88 })), ]) .jpeg({ quality: 90 }) .toBuffer(); }