最近在做 og image
因為不太想要一個一個做 og image 的圖片
所以在看官方文件時發現有 ImageResponse 的函式可以使用
因為是要呈現動態圖片
所以放置的方式是在動態資料夾底下
路徑:app/writings/[slug]/opengraph-image.tsx
只能用 style 方式寫樣式,寫 className 會無法顯示圖片
export default async function Image({ params }: { params: { slug: string } }) {
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'white',
}}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
fontSize: 48,
color: '#55534F',
}}
>
{name || 'No result found'}
</div>
</div>
),
{
width: 1200,
height: 600,
);
}
如果想自訂字型可以使用 readFile 請求
import { ImageResponse } from 'next/og';
import { HikeDataProps } from '@/types/types';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { fetchNotionPageContent } from '@/utils/notion-api';
import { PageObjectResponse } from '@notionhq/client/build/src/api-endpoints';
export const size = {
width: 1200,
height: 630,
};
export const contentType = 'image/png';
export default async function Image({ params }: { params: { slug: string } }) {
const { slug } = await params;
const { info } = await fetchNotionPageContent(slug);
const { properties } = (info as PageObjectResponse) || {};
let name = '';
if (properties?.name && properties?.name?.type === 'title') {
name = properties?.name?.title?.[0]?.plain_text;
}
// 字體載入,process.cwd() 是 Next.js 專案目錄
const NotoSansTCBlack = await readFile(
join(process.cwd(), 'public/fonts/NotoSansTC-Black.ttf'),
);
return new ImageResponse(
(
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'white',
}}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
fontSize: 48,
color: '#55534F',
}}
>
{name || 'No result found'}
</div>
</div>
),
{
...size,
fonts: [
{
name: 'Noto Sans TC',
data: NotoSansTCBlack,
},
],
},
);
}
最後就可以預覽 og 圖喇 ✌️