mirror of
https://github.com/ChenQihan666/MyBlog-Next.git
synced 2026-08-14 11:29:33 +08:00
feat: generate og image using templates
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
import satori, { type SatoriOptions } from "satori";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { Resvg } from "@resvg/resvg-js";
|
||||
import { getCollection } from "astro:content";
|
||||
import { type CollectionEntry } from "astro:content";
|
||||
import postOgImage from "./og-templates/post";
|
||||
import siteOgImage from "./og-templates/site";
|
||||
|
||||
const fetchFonts = async () => {
|
||||
// Regular Font
|
||||
@@ -42,42 +42,18 @@ const options: SatoriOptions = {
|
||||
],
|
||||
};
|
||||
|
||||
const generateOgImages = async () => {
|
||||
const postImportResult = await getCollection(
|
||||
"blog",
|
||||
({ data }) => !data.draft
|
||||
);
|
||||
const posts = Object.values(postImportResult).filter(
|
||||
({ data }) => !data.ogImage
|
||||
);
|
||||
function svgBufferToPngBuffer(svg: string) {
|
||||
const resvg = new Resvg(svg);
|
||||
const pngData = resvg.render();
|
||||
return pngData.asPng();
|
||||
}
|
||||
|
||||
const imageGenerationPromises = posts.map(async post => {
|
||||
const svg = await satori(postOgImage(post.data.title), options);
|
||||
export async function generateOgImageForPost(post: CollectionEntry<"blog">) {
|
||||
const svg = await satori(postOgImage(post), options);
|
||||
return svgBufferToPngBuffer(svg);
|
||||
}
|
||||
|
||||
// render png in production mode
|
||||
if (import.meta.env.MODE === "production") {
|
||||
const resvg = new Resvg(svg);
|
||||
const pngData = resvg.render();
|
||||
const pngBuffer = pngData.asPng();
|
||||
|
||||
const outputImage = `${post.slug}.png`;
|
||||
|
||||
const LIGHT_BLUE = "\x1b[94m";
|
||||
const DARK_GRAY = "\x1b[30m";
|
||||
const RESET = "\x1b[0m";
|
||||
console.info(
|
||||
` ${LIGHT_BLUE}└─${RESET} output png image:`,
|
||||
`${DARK_GRAY}/${outputImage}${RESET}`
|
||||
);
|
||||
|
||||
await writeFile(`./dist/${outputImage}`, pngBuffer);
|
||||
}
|
||||
});
|
||||
|
||||
// Wait for all image generation operations to complete
|
||||
await Promise.all(imageGenerationPromises);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default generateOgImages;
|
||||
export async function generateOgImageForSite() {
|
||||
const svg = await satori(siteOgImage(), options);
|
||||
return svgBufferToPngBuffer(svg);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user