原文章:Dynamic OG image generation in AstroPaper blog posts
AstroPaper v1.4.0中的新功能,引入了博客文章的动态OG图片生成
Table of contents
Open Table of contents
介绍
OG图片(也称为社交图片)在社交媒体互动中扮演着重要角色。如果你不知道OG图片是什么意思,它是在我们在社交媒体(如Facebook、Discord等)分享网站URL时显示的图片。
在Twitter上使用的社交图片在技术上并不称为OG图片。然而,在这篇文章中,我将使用OG图片一词来指代所有类型的社交图片。
默认/静态OG图片(旧方式)
AstroPaper 已经提供了一种将OG图片添加到博客文章的方法。作者可以在前言中指定OG图片为 ogImage。即使作者没有在前言中定义OG图片,默认OG图片也会作为后备使用(在这种情况下为 public/astropaper-og.jpg)。但问题是,默认OG图片是静态的,这意味着每个不包括OG图片的博客文章将始终使用相同的默认OG图片,尽管每篇文章的标题/内容与其他文章不同
动态OG图片
为每篇文章生成动态OG图片允许作者避免为每一篇博客文章指定OG图片。此外,这将防止后备OG图片在所有博客文章中相同。
在AstroPaper v1.4.0中,使用 Vercel 的Satori 包进行动态OG图片生成。
动态OG图片将在构建时为以下博客文章生成:
- 不在
Frontmatter中包含OG图片 - 没有标记为草稿的文章
AstroPaper动态OG图片的构成
Dynamic OG image of AstroPaper includes the blog post title, author name and site title. Author name and site title will be retrieved via SITE.author and SITE.title of “src/config.ts” file. The title is generated from the blog post frontmatter title.
AstroPaper的动态OG图片包含 博客文章标题 、作者名称 和 网站标题。作者名称和网站标题将通过 SITE.author 和 SITE.title 从 "src/config.ts" 文件中获取。标题是从博客文章前言的 title 生成的。

非拉丁字符问题
带有非拉丁字符的标题在默认情况下不会正确显示。为了解决这个问题,我们必须在 loadGoogleFont.ts 中替换 fontsConfig 为你喜欢的字体。
async function loadGoogleFonts(
text: string
): Promise<
Array<{ name: string; data: ArrayBuffer; weight: number; style: string }>
> {
const fontsConfig = [
{
name: "Noto Sans JP",
font: "Noto+Sans+JP",
weight: 400,
style: "normal",
},
{
name: "Noto Sans JP",
font: "Noto+Sans+JP:wght@700",
weight: 700,
style: "normal",
},
{ name: "Noto Sans", font: "Noto+Sans", weight: 400, style: "normal" },
{
name: "Noto Sans",
font: "Noto+Sans:wght@700",
weight: 700,
style: "normal",
},
];
// ...
}src/utils/loadGoogleFont.ts
详情请查看这个PR。
权衡
虽然这是一个不错的功能,但也有权衡。每个OG图片大约需要一秒钟生成。起初可能不会明显,但随着博客文章数量的增加,你可能会想要禁用此功能。因为每个OG图片都需要时间生成,拥有大量OG图片将线性增加构建时间。
例如:如果一个OG图片需要一秒钟生成,那么60个图片将大约需要一分钟,而600个图片将大约需要10分钟。随着内容的扩展,这可能会显著影响构建时间。
相关问题:#428
限制
At the time of writing this, Satori is fairly new and has not reached major release yet. So, there are still some limitations to this dynamic OG image feature.
在撰写本文时,Satori相对较新,尚未达到主要版本。因此,此动态OG图片功能仍存在一些限制。
- 此外,RTL语言尚不支持
- 在标题中使用表情符号(Emoji)可能会有点棘手