Automated OG Image Generation Build Dynamic Social Cards with a Screenshot API
停止手动创建社交预览图像。 了解如何使用 HTML 模板和屏幕截图 API 动态生成精美的 OG 图像。 代码丰富的教程,包含真实示例。
您花几个小时精心制作完美的博文,点击发布,然后在 Twitter 上分享。然后……一个乏味的灰色框。没有预览。没有图片。只有一个没有人想点击的、悲伤的、赤裸裸的链接。
听起来很熟悉?OG(Open Graph)图片是社交分享的无名英雄。它们确实是您的内容被滚动 past 还是被点击的区别。如果您仍然在 Figma 中为每个页面手动创建它们,那么我们需要谈谈了。
什么是 OG 图片(以及您为什么应该关心)?
OG 图片是在您在社交媒体、Slack、Discord 或任何可以展开 URL 的地方分享链接时出现的预览卡片。它们在您的 HTML 中定义 <meta> 标签:
<meta property="og:image" content="https://yoursite.com/og/your-page.png" />
<meta property="og:title" content="Your Awesome Title" />
<meta property="og:description" content="A compelling description" />
问题是?手动创建这些图片无法规模化。有 100 篇博文?那就是 100 张图片。有动态产品页面?祝您跟上。
解决方案:即时生成 OG 图片
这样操作:与其预先生成图片,不如实时渲染 HTML 模板并使用截图 API 对其进行截图。流程如下:
- 创建 OG 卡的 HTML 模板
- 使用动态参数(标题、作者等)托管它
- 将您的
og:imagemeta 标签指向截图 API - 完成。每页都有一个独特的、精美的预览卡片。
第 1 步:构建您的 OG 模板
首先,创建一个简单的 HTML 页面来渲染您的社交卡片。这可以是您应用中的一个专用路由或一个静态 HTML 文件。
<!-- /og-template?title=Hello%20World&author=John -->
<!DOCTYPE html>
<html>
<head>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
width: 1200px;
height: 630px;
display: flex;
flex-direction: column;
justify-content: center;
padding: 60px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
font-family: system-ui, sans-serif;
color: white;
}
h1 {
font-size: 64px;
font-weight: 800;
line-height: 1.1;
margin-bottom: 24px;
}
.author {
font-size: 28px;
opacity: 0.9;
}
.logo {
position: absolute;
bottom: 40px;
right: 60px;
font-size: 24px;
font-weight: 600;
}
</style>
</head>
<body>
<h1 id="title">Your Title Here</h1>
<p class="author">by <span id="author">Author Name</span></p>
<div class="logo">yoursite.com</div>
<script>
const params = new URLSearchParams(window.location.search);
document.getElementById('title').textContent = params.get('title') || 'Untitled';
document.getElementById('author').textContent = params.get('author') || 'Anonymous';
</script>
</body>
</html>
这里的关键是: 1200x630 像素。这是 OG 图片的理想尺寸。Twitter、Facebook、LinkedIn — 它们都支持此尺寸。
第 2 步:使用 API 截图
现在是乐趣所在。与其在服务器上运行 Puppeteer(并处理所有无头 Chrome 的麻烦),不如使用截图 API 来渲染您的模板。
这是一个 Node.js 示例,展示了通用模式:
// Generate OG image URL using a screenshot API
function getOgImageUrl(title, author) {
const templateUrl = encodeURIComponent(
`https://yoursite.com/og-template?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`
);
// Most screenshot APIs follow this pattern:
// Pass your template URL + dimensions, get back an image
return `https://your-screenshot-api.com/capture?` +
`url=${templateUrl}` +
`&width=1200` +
`&height=630` +
`&format=png`;
}
第 3 步:将其集成到您的 Meta 标签中
在您页面的 <head>中,动态设置 OG 图片:
// Next.js example (pages/_app.js or layout.tsx)
import Head from 'next/head';
export default function BlogPost({ post }) {
const ogImage = getOgImageUrl(post.title, post.author);
return (
<>
<Head>
<meta property="og:image" content={ogImage} />
<meta property="og:title" content={post.title} />
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:image" content={ogImage} />
</Head>
<article>{/* Your content */}</article>
</>
);
}
第 4 步:添加缓存(重要!)
您不希望在 Twitter 的爬虫每次检查您的页面时都调用 API。设置一个缓存层:
// Edge function example (Vercel/Cloudflare)
export default async function handler(req) {
const { title, author } = req.query;
// Call your screenshot API
const screenshotUrl = buildScreenshotUrl({
url: `https://yoursite.com/og-template?title=${title}&author=${author}`,
width: 1200,
height: 630,
format: 'png'
});
const response = await fetch(screenshotUrl);
const imageBuffer = await response.arrayBuffer();
return new Response(imageBuffer, {
headers: {
'Content-Type': 'image/png',
'Cache-Control': 'public, max-age=86400, s-maxage=604800', // Cache for a week
},
});
}
现在您的 meta 标签指向您自己的端点,该端点缓存结果:
<meta property="og:image" content="https://yoursite.com/api/og?title=My%20Post&author=John" />
Pro Tips 🔥
- 使用网页字体: Google Fonts 效果很好。只需确保它们在截图触发之前加载即可。
- 添加您的品牌: Logo、渐变、图案 — 让它在信息流中易于识别。
- 保持文本大: 社交卡片通常被视为缩略图。标题为 48px 或更高。
- 使用验证器测试: 使用 Twitter 的卡片验证器 和 和 Facebook 的调试器
进行预览。
实际示例
- 这个模式被一些最好的开发博客使用: Vercel/Next.js:
- 他们的 OG 图片包含帖子标题、日期和阅读时间 GitHub:
- 仓库卡片显示星标、fork 数和描述 Dev.to:
文章卡片包含作者头像和点赞数
您可以在 20 分钟内使用截图 API 完成同样的事情。无需维护基础设施,也无需处理 Chromium 二进制文件。
// Full working example with error handling
async function generateOgImage(title, author, category) {
const templateParams = new URLSearchParams({
title: title.slice(0, 60), // Truncate long titles
author,
category: category || 'Blog'
});
const templateUrl = `https://yoursite.com/og-template?${templateParams}`;
try {
// Adapt this to your screenshot API of choice
const response = await fetch(SCREENSHOT_API_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.SCREENSHOT_API_KEY}`
},
body: JSON.stringify({
url: templateUrl,
viewport: { width: 1200, height: 630 },
format: 'png',
waitUntil: 'networkidle' // Wait for fonts/images to load
})
});
if (!response.ok) throw new Error('Screenshot failed');
return await response.arrayBuffer();
} catch (error) {
console.error('OG generation failed:', error);
// Return a fallback image
return fetch('https://yoursite.com/default-og.png').then(r => r.arrayBuffer());
}
}
完整流程
为什么使用截图 API 而不是自托管? 您 可以
- 自己运行 Puppeteer。但实际情况是这样的:
- 600MB+ 的 Docker 镜像包含 Chromium
- 内存飙升导致服务器崩溃
- 僵尸进程困扰您的容器
不同环境下的字体渲染问题
立即开始
或者您可以……不这样做。截图 API 解决了所有这些问题,您只需按截图付费,而不是按服务器小时付费。对于大多数网站来说,这会便宜得多。 准备好让您的社交分享看起来更专业了吗?查看 Snapopa
Your Twitter game is about to level up. 📈
