feat: generate og image using templates

This commit is contained in:
tanishqmanuja
2023-09-20 15:48:31 +05:30
committed by Sat Naing
parent b5308debab
commit 3032c18321
2 changed files with 102 additions and 39 deletions
+15 -39
View File
@@ -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);
}