52 lines
2.5 KiB
TypeScript
52 lines
2.5 KiB
TypeScript
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<Buffer> {
|
|
const lines = headlineLines(headline);
|
|
if (!lines.length) return image;
|
|
const svg = `<svg width="1024" height="1024" xmlns="http://www.w3.org/2000/svg">
|
|
<defs><linearGradient id="shade" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#101820" stop-opacity="0"/><stop offset="0.28" stop-color="#101820" stop-opacity="0.82"/><stop offset="1" stop-color="#101820" stop-opacity="0.97"/></linearGradient></defs>
|
|
<rect x="0" y="500" width="1024" height="524" fill="url(#shade)"/>
|
|
<rect x="64" y="590" width="112" height="9" rx="4" fill="${escapeXml(accent)}"/>
|
|
</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();
|
|
}
|