0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Astro + satori】動的なOGP画像をつくろう

0
Posted at

はじめに

今年の10月に開催した本校の文化祭である茨香祭のHP開発にて、OGP画像の自動生成の実装を担当しました。出展サークルやイベントごとに紹介画像と紹介文を含む画像を生成しています。

この記事では、その実装から最小限の要素を抜き出し各ページのOGP画像を生成するサンプルを作成します。

定義

この記事では「ページごとの内容から、ビルド時に画像を自動生成すること」を動的OGPと呼びます。リクエストの度にサーバーで画像を生成する方式は対象外としています。

各方式の比較は以下の通りです。

方式 画像を作成する時点 適している条件
静的ファイル 手動で事前に作成 ページ数が少なく、内容が変わらない
ビルド時に生成 ビルドの実行時 静的サイトで、ページ数がビルド時に確定する
リクエスト時に生成 アクセス毎 ページ数が確定しない or サーバー実行環境がある

動作環境

今回、開発および動作に使用した環境は以下のとおりです。

  • PC:MacBook Pro M4(16GBモデル)
  • エディタ:VSCode
  • Node.js v22
  • astro v7.4.11
  • @astrojs/react 7.1.8
  • satori v0.63.2
  • sharp v0.35.5
  • @fontsource/noto-sans-jp v5.3.1

実装

それでは実装していきましょう。処理の流れは以下のとおりです。

  1. JSXで画像のレイアウトを記述する
  2. satoriがJSXをSVGに変換する
  3. sharpがSVGをPNGに変換する
  4. Astroの静的エンドポイントが、ビルド時にPNGをファイルとして出力する

1. プロジェクトのセットアップ

まずはプロジェクトとコンテンツを準備しましょう。ターミナルで以下のコマンドを叩いてください。

npm create astro@latest ogp-handson -- --template minimal
cd ogp-handson
npx astro add react
npm install satori sharp @fontsource/noto-sans-jp
npm install -D @types/node

@astrojs/reactは、レイアウトをJSXで記述するために使用します。@types/nodeはnode:fsの型の定義です。

node:fsはNode.jsの標準モジュールで、ファイルの読み書きに使用します。標準モジュールのため追加インストールは不要です。

次にastro.config.mjsに公開先のURLに指定します。og:imageは絶対URLで出力する必要があるためです。

astro.config.mjs
// @ts-check
import { defineConfig } from 'astro/config';

import react from '@astrojs/react';

// https://astro.build/config
export default defineConfig({
  // og:image は絶対 URL で出力する必要があるため、公開先の URL を設定する。
  site: 'https://example.com',
  integrations: [react()]
});

記事のコレクションも定義します。

src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const posts = defineCollection({
	loader: glob({ pattern: '**/*.md', base: './src/content/posts' }),
	schema: z.object({
		title: z.string(),
		description: z.string(),
	}),
});

export const collections = { posts };

src/content/posts/にmdファイルを3件追加します。

src/content/posts/first-post.md
---
title: はじめての投稿
description: Astroでブログを作成しました。このサイトの構成を紹介します。
---

本文です。
src/content/posts/dynamic-ogp.md
---
title: Astroとsatoriで記事ごとのOGP画像をビルド時に自動生成する方法
description: 記事のタイトルと説明文から、SNS共有用の画像を1200×630ピクセルで生成します。画像編集ソフトは使用しません。
---

本文です。
src/content/posts/emoji.md
---
title: 文化祭のWebサイトを公開しました🎉
description: タイトルに絵文字を含む記事の例です。
---

本文です。

続いて、レイアウトとページを作成します。

src/layouts/Layout.astro
---
interface Props {
	title: string;
	description: string;
}

const { title, description } = Astro.props;
---

<html lang="ja">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width" />
		<title>{title}</title>
		<meta name="description" content={description} />
	</head>
	<body>
		<slot />
	</body>
</html>
src/pages/index.astro
---
import { getCollection } from 'astro:content';
import Layout from '../layouts/Layout.astro';

const posts = await getCollection('posts');
---

<Layout title="OGP Handson Blog" description="動的OGPのハンズオン用サンプルサイトです。">
	<h1>OGP Handson Blog</h1>
	<ul>
		{posts.map((post) => (
			<li><a href={`/posts/${post.id}/`}>{post.data.title}</a></li>
		))}
	</ul>
</Layout>
src/pages/posts/[slug].astro
---
import { getCollection, render } from 'astro:content';
import Layout from '../../layouts/Layout.astro';

export async function getStaticPaths() {
	const posts = await getCollection('posts');
	return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---

<Layout title={post.data.title} description={post.data.description}>
	<h1>{post.data.title}</h1>
	<Content />
</Layout>

確認としてビルドを実行しましょう。npm run buildを実行し、dist/posts/に3つのHTMLが出力されれば完了です。

2. 固定の画像を1枚生成する

最初に英数字だけの画像を1枚生成します。

src/lib/og/card.tsx
import fs from 'node:fs';
import path from 'node:path';
import satori from 'satori';
import sharp from 'sharp';

export const OG_WIDTH = 1200;
export const OG_HEIGHT = 630;

const SITE_NAME = 'OGP Handson Blog';

// 英数字だけを収録したファイル。日本語は Step 3 で対応する。
const FONT_PATH = path.resolve('node_modules/@fontsource/noto-sans-jp/files/noto-sans-jp-latin-700-normal.woff2');

export interface OgCardInput {
	title: string;
	description: string;
}

export async function renderOgCard({ title, description }: OgCardInput): Promise<Buffer> {
	// 1. JSX を SVG の文字列に変換する。
	const svg = await satori(
		<div
			style={{
				display: 'flex',
				flexDirection: 'column',
				justifyContent: 'space-between',
				boxSizing: 'border-box',
				width: OG_WIDTH,
				height: OG_HEIGHT,
				padding: 72,
				backgroundColor: '#0f172a',
				color: '#f8fafc',
				borderLeft: '24px solid #38bdf8',
			}}
		>
			<div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
				<div style={{ fontSize: 64, lineHeight: 1.3, lineClamp: 3 }}>{title}</div>
				<div style={{ fontSize: 30, lineHeight: 1.6, lineClamp: 2, color: '#cbd5e1' }}>{description}</div>
			</div>
			<div style={{ fontSize: 32, color: '#38bdf8' }}>{SITE_NAME}</div>
		</div>,
		{
			width: OG_WIDTH,
			height: OG_HEIGHT,
			fonts: [{ name: 'Noto Sans JP', data: fs.readFileSync(FONT_PATH), weight: 700, style: 'normal' }],
		},
	);

	// 2. SVG を PNG に変換する。
	return sharp(Buffer.from(svg)).png().toBuffer();
}

要点は以下の3つです。

  • satoriにはフォントのデータを必ず渡す(システムのデフォルトのフォントは使用されない)
  • boxSizing: 'border-box'を指定する
    • 指定しない場合、paddingの分だけ要素が630pxを超え、下端のサイト名が画像の範囲外になる
  • lineClampは指定した行数を超えた文字を省略する

次に画像を返すエンドポイントを作成します。ファイル名をhome.png.tsにすると、ビルド時に/og/home.pngが出力されます。

src/pages/og/home.png.ts
import type { APIRoute } from 'astro';
import { renderOgCard } from '../../lib/og/card';

export const GET: APIRoute = async () => {
	const png = await renderOgCard({
		title: 'OGP Handson Blog',
		description: 'A sample site for generating Open Graph images at build time.',
	});
	return new Response(new Uint8Array(png), { headers: { 'Content-Type': 'image/png' } });
};

再度、開発サーバーを起動しましょう。http://localhost:4321/og/home.pngをブラウザで開きます。

step2-home-latin.png

3. 日本語フォントに対応する

home.png.tsのdescriptionを日本語に変更する。

-		description: 'A sample site for generating Open Graph images at build time.',
+		description: '動的OGPのハンズオン用サンプルサイトです。',

再度表示すると、日本語の箇所が◻︎で伏せ字のようになっているはずです。エラーは発生しません。これは先ほど渡したファイルが英数字しか収録されていないためです。

step3-home-tofu.png

この伏せ字を直すために、日本語で必要な分割ファイルだけ渡しましょう。@fontsource/noto-sans-jpは、1つのウェイトを124個のファイルに分割して配布しています(以下、分割された各ファイルを「スライス」と呼びます)。700.cssには、各スライスが収録する文字コードの範囲がunicode-rangeとして記述されています。

ウェイト700のwoff2は合計で約3.0MBです。一方、サンプルの記事「dynamic-ogp」の描画に必要なスライスは10個、合計で約136KBでした。そこで、画像に描画する文字を含むスライスだけ選択してsatoriに渡します。

src/lib/og/fonts.ts
import fs from 'node:fs';
import path from 'node:path';
import type { Font } from 'satori';

const FONT_DIR = path.resolve('node_modules/@fontsource/noto-sans-jp');
const WEIGHT = 700;

interface FontSlice {
	/** 分割されたフォントファイルの名前。 */
	file: string;
	/** このファイルが収録している文字コードの範囲。 */
	ranges: [number, number][];
}

let slices: FontSlice[] | undefined;

/** 700.css の @font-face から、ファイル名と unicode-range の対応を読み取る。 */
function loadSlices(): FontSlice[] {
	if (slices) return slices;
	const css = fs.readFileSync(path.join(FONT_DIR, `${WEIGHT}.css`), 'utf8');
	slices = [...css.matchAll(/@font-face\s*{[^}]*}/g)].flatMap(([block]): FontSlice[] => {
		const file = block.match(/files\/([\w-]+\.woff2)\)/)?.[1];
		const range = block.match(/unicode-range:\s*([^;]+);/)?.[1];
		if (!file || !range) return [];
		const ranges = range.split(',').map((part): [number, number] => {
			const [from = '', to = from] = part.trim().replace(/^U\+/i, '').split('-');
			return [parseInt(from, 16), parseInt(to, 16)];
		});
		return [{ file, ranges }];
	});
	return slices;
}

const covers = (slice: FontSlice, code: number) => slice.ranges.some(([from, to]) => code >= from && code <= to);

/** フォントに収録されていない文字(絵文字など)を取り除く。 */
export function stripUnsupportedGlyphs(text: string): string {
	return [...text].filter((char) => loadSlices().some((slice) => covers(slice, char.codePointAt(0)!))).join('');
}

/** text の描画に必要なスライスだけを、satori の fonts オプションの形式で返す。 */
export function fontsFor(text: string): Font[] {
	const codes = [...new Set([...text].map((char) => char.codePointAt(0)!))];
	return loadSlices()
		.filter((slice) => codes.some((code) => covers(slice, code)))
		.map((slice) => ({
			// 同じ名前のフォントを複数渡すと 1 つしか使用されないため、ファイル名を名前にする。
			name: slice.file,
			data: fs.readFileSync(path.join(FONT_DIR, 'files', slice.file)),
			weight: WEIGHT,
			style: 'normal',
		}));
}

注意すべき点は2つです。

  • スライスごとに異なる名前を指定します。全てのスライスに同じ名前Noto Sans JPを指定して試したところ、1つのスライスしか使用されず大半の文字が◻︎になりました。異なる名前を指定し、fontFamilyを指定しない場合は、渡した全てのスライスから文字が検索されました。
  • 収録されていない文字は事前に除去します。絵文字はNoto Sans JPに収録されておらず、◻︎で描画されます。stripUnsupportedGlyphsで除去します。

step3-emoji-without-strip.png

card.tsxを次のように変更します。

src/lib/og/card.tsx
-import fs from 'node:fs';
-import path from 'node:path';
 import satori from 'satori';
 import sharp from 'sharp';
+import { fontsFor, stripUnsupportedGlyphs } from './fonts';

-// 英数字だけを収録したファイル。日本語は Step 3 で対応する。
-const FONT_PATH = path.resolve('node_modules/@fontsource/noto-sans-jp/files/noto-sans-jp-latin-700-normal.woff2');

-export async function renderOgCard({ title, description }: OgCardInput): Promise<Buffer> {
+export async function renderOgCard(input: OgCardInput): Promise<Buffer> {
+	const title = stripUnsupportedGlyphs(input.title);
+	const description = stripUnsupportedGlyphs(input.description);

-			fonts: [{ name: 'Noto Sans JP', data: fs.readFileSync(FONT_PATH), weight: 700, style: 'normal' }],
+			// 画像に描画する文字を含むスライスだけを渡す。
+			fonts: fontsFor(title + description + SITE_NAME),

http://localhost:4321/og/home.pngを再度開いて、日本語が描画されていれば完了です。

step3-home-japanese.png

4. 記事ごとに画像を生成する

getStaticPathsで記事の一覧を返すと、Astroが記事の件数分エンドポイントを実行します。記述方法はsrc/pages/posts/[slug].astroと同じです。

src/pages/og/[slug].astro
import type { APIRoute, GetStaticPaths } from 'astro';
import { getCollection } from 'astro:content';
import { renderOgCard } from '../../lib/og/card';

// 記事 1 件につき 1 つのパス(/og/<記事ID>.png)を返す。
export const getStaticPaths = (async () => {
	const posts = await getCollection('posts');
	return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));
}) satisfies GetStaticPaths;

export const GET: APIRoute = async ({ props }) => {
	const { title, description } = props.post.data;
	const png = await renderOgCard({ title, description });
	return new Response(new Uint8Array(png), { headers: { 'Content-Type': 'image/png' } });
};

http://localhost:4321/og/dynamic-ogp.pngを開きます。

step4-dynamic-ogp.png

emoji.pngでは、タイトルの絵文字が除去されていることを確認できます。

step4-emoji.png

5. metaタグを出力する

Layout.astroを次の内容に置き換えます。

src/layouts/Layout.astro
---
interface Props {
	title: string;
	description: string;
	/** OGP 画像のパス(例: /og/first-post.png)。 */
	ogImage: string;
}

const { title, description, ogImage } = Astro.props;

// og:url と og:image は絶対 URL で出力する。Astro.site は astro.config.mjs の site の値。
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
const ogImageURL = new URL(ogImage, Astro.site);
---

<html lang="ja">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width" />
		<title>{title}</title>
		<meta name="description" content={description} />
		<meta property="og:title" content={title} />
		<meta property="og:description" content={description} />
		<meta property="og:type" content="website" />
		<meta property="og:url" content={canonicalURL} />
		<meta property="og:image" content={ogImageURL} />
		<meta property="og:image:width" content="1200" />
		<meta property="og:image:height" content="630" />
		<meta name="twitter:card" content="summary_large_image" />
	</head>
	<body>
		<slot />
	</body>
</html>

各ページから画像のパスを渡します。

src/pages/index.astro
-<Layout title="OGP Handson Blog" description="動的OGPのハンズオン用サンプルサイトです。">
+<Layout title="OGP Handson Blog" description="動的OGPのハンズオン用サンプルサイトです。" ogImage="/og/home.png">
src/pages/posts/[slug].astro
-<Layout title={post.data.title} description={post.data.description}>
+<Layout title={post.data.title} description={post.data.description} ogImage={`/og/${post.id}.png`}>

ビルド結果を確認する

ビルドして確認しましょう。

npm run build

ビルドとログに、画像4枚の生成が出力されます。

├─ /og/home.png (+106ms)
├─ /og/dynamic-ogp.png (+67ms)
├─ /og/emoji.png (+52ms)
├─ /og/first-post.png (+44ms)

dist/posts/first-post/index.htmlには、次のタグが出力されます。

<meta property="og:image" content="https://example.com/og/first-post.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">

デプロイ後は、SNSやチャットツールの投稿欄にURLを貼り付けて、プレビューの表示を確認します。SNS側が画像をキャッシュするため、画像を変更した直後は変更前の画像が表示される場合があります。

おわりに

今回は動的なOGP画像の生成についてチュートリアル形式でまとめました。Web系のチュートリアルは初めてだったので(1度だけZennでLeanの入門記事を書いた経験アリ)、不恰好ながらも最後まで書けて良かったです!

OGP画像はURL共有に花を添えられる非機能要件としてUXの向上を支えられる素晴らしい技術です。ぜひ開発で取り入れてみてください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?