主题
opengraph 图片和 twitter 图片 
¥opengraph-image and twitter-image
opengraph-image 和 twitter-image 文件约定允许你为路由段设置 Open Graph 和 Twitter 图片。
¥The opengraph-image and twitter-image file conventions allow you to set Open Graph and Twitter images for a route segment.
当用户共享指向你网站的链接时,它们可用于设置社交网络和消息应用上显示的图片。
¥They are useful for setting the images that appear on social networks and messaging apps when a user shares a link to your site.
设置 Open Graph 和 Twitter 图片有两种方法:
¥There are two ways to set Open Graph and Twitter images:
图片文件(.jpg、.png、.gif) 
¥Image files (.jpg, .png, .gif)
使用图片文件通过在路段中放置 opengraph-image 或 twitter-image 图片文件来设置路段的共享图片。
¥Use an image file to set a route segment's shared image by placing an opengraph-image or twitter-image image file in the segment.
Next.js 将评估该文件并自动将适当的标签添加到应用的 <head> 元素中。
¥Next.js will evaluate the file and automatically add the appropriate tags to your app's <head> element.
| 文件约定 | 支持的文件类型 | 
|---|---|
opengraph-image | .jpg, .jpeg, .png, .gif | 
twitter-image | .jpg, .jpeg, .png, .gif | 
opengraph-image.alt | .txt | 
twitter-image.alt | .txt | 
需要了解:
¥Good to know:
twitter-image文件大小不得超过 5MB,opengraph-image文件大小不得超过 8MB。如果图片文件大小超出这些限制,则构建将失败。¥The
twitter-imagefile size must not exceed 5MB, and theopengraph-imagefile size must not exceed 8MB. If the image file size exceeds these limits, the build will fail.
opengraph-image 
将 opengraph-image.(jpg|jpeg|png|gif) 图片文件添加到任何路由段。
¥Add an opengraph-image.(jpg|jpeg|png|gif) image file to any route segment.
html
<meta property="og:image" content="<generated>" />
<meta property="og:image:type" content="<generated>" />
<meta property="og:image:width" content="<generated>" />
<meta property="og:image:height" content="<generated>" />twitter-image 
将 twitter-image.(jpg|jpeg|png|gif) 图片文件添加到任意路段。
¥Add a twitter-image.(jpg|jpeg|png|gif) image file to any route segment.
html
<meta name="twitter:image" content="<generated>" />
<meta name="twitter:image:type" content="<generated>" />
<meta name="twitter:image:width" content="<generated>" />
<meta name="twitter:image:height" content="<generated>" />opengraph-image.alt.txt 
在与 opengraph-image.(jpg|jpeg|png|gif) 图片相同的路由段中添加随附的 opengraph-image.alt.txt 文件(它是替代文本)。
¥Add an accompanying opengraph-image.alt.txt file in the same route segment as the opengraph-image.(jpg|jpeg|png|gif) image it's alt text.
txt
About Acmehtml
<meta property="og:image:alt" content="About Acme" />twitter-image.alt.txt 
在与 twitter-image.(jpg|jpeg|png|gif) 图片相同的路由段中添加随附的 twitter-image.alt.txt 文件(它是替代文本)。
¥Add an accompanying twitter-image.alt.txt file in the same route segment as the twitter-image.(jpg|jpeg|png|gif) image it's alt text.
txt
About Acmehtml
<meta property="twitter:image:alt" content="About Acme" />使用代码(.js、.ts、.tsx)生成图片 
¥Generate images using code (.js, .ts, .tsx)
除了使用 字面量图片文件 之外,你还可以使用代码以编程方式生成图片。
¥In addition to using literal image files, you can programmatically generate images using code.
通过创建默认导出函数的 opengraph-image 或 twitter-image 路由来生成路由段的共享映像。
¥Generate a route segment's shared image by creating an opengraph-image or twitter-image route that default exports a function.
| 文件约定 | 支持的文件类型 | 
|---|---|
opengraph-image | .js, .ts, .tsx | 
twitter-image | .js, .ts, .tsx | 
需要了解:
¥Good to know:
默认情况下,生成的图片是 静态优化(在构建时生成并缓存),除非它们使用 动态 API 或未缓存的数据。
¥By default, generated images are statically optimized (generated at build time and cached) unless they use Dynamic APIs or uncached data.
你可以使用
generateImageMetadata在同一个文件中生成多个图片。¥You can generate multiple Images in the same file using
generateImageMetadata.
opengraph-image.js和twitter-image.js是特殊的路由处理程序,除非使用 动态 API 或 动态配置 选项,否则默认情况下会缓存。¥
opengraph-image.jsandtwitter-image.jsare special Route Handlers that is cached by default unless it uses a Dynamic API or dynamic config option.
生成图片的最简单方法是使用 next/og 中的 ImageResponse API。
¥The easiest way to generate an image is to use the ImageResponse API from next/og.
tsx
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
// Image metadata
export const alt = 'About Acme'
export const size = {
  width: 1200,
  height: 630,
}
export const contentType = 'image/png'
// Image generation
export default async function Image() {
  // Font loading, process.cwd() is Next.js project directory
  const interSemiBold = await readFile(
    join(process.cwd(), 'assets/Inter-SemiBold.ttf')
  )
  return new ImageResponse(
    (
      // ImageResponse JSX element
      <div
        style={{
          fontSize: 128,
          background: 'white',
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        About Acme
      </div>
    ),
    // ImageResponse options
    {
      // For convenience, we can re-use the exported opengraph-image
      // size config to also set the ImageResponse's width and height.
      ...size,
      fonts: [
        {
          name: 'Inter',
          data: interSemiBold,
          style: 'normal',
          weight: 400,
        },
      ],
    }
  )
}html
<meta property="og:image" content="<generated>" />
<meta property="og:image:alt" content="About Acme" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />属性 
¥Props
默认导出函数接收以下属性:
¥The default export function receives the following props:
params(可选) 
¥params (optional)
包含从根段到段 opengraph-image 或 twitter-image 的 动态路由参数 对象的对象位于同一位置。
¥An object containing the dynamic route parameters object from the root segment down to the segment opengraph-image or twitter-image is colocated in.
tsx
export default function Image({ params }: { params: { slug: string } }) {
  // ...
}| 路由 | URL | params | 
|---|---|---|
app/shop/opengraph-image.js | /shop | undefined | 
app/shop/[slug]/opengraph-image.js | /shop/1 | { slug: '1' } | 
app/shop/[tag]/[item]/opengraph-image.js | /shop/1/2 | { tag: '1', item: '2' } | 
返回 
¥Returns
默认导出函数应返回 Blob | ArrayBuffer | TypedArray | DataView | ReadableStream | Response。
¥The default export function should return a Blob | ArrayBuffer | TypedArray | DataView | ReadableStream | Response.
需要了解:
ImageResponse满足此返回类型。¥Good to know:
ImageResponsesatisfies this return type.
配置导出 
¥Config exports
你可以选择通过从 opengraph-image 或 twitter-image 路由导出 alt、size 和 contentType 变量来配置图片的元数据。
¥You can optionally configure the image's metadata by exporting alt, size, and contentType variables from opengraph-image or twitter-image route.
| 选项 | 类型 | 
|---|---|
alt | string | 
size | { width: number; height: number } | 
contentType | string - 图片 MIME 类型 | 
alt 
tsx
export const alt = 'My images alt text'
export default function Image() {}html
<meta property="og:image:alt" content="My images alt text" />size 
tsx
export const size = { width: 1200, height: 630 }
export default function Image() {}html
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />contentType 
tsx
export const contentType = 'image/png'
export default function Image() {}html
<meta property="og:image:type" content="image/png" />路由片段配置 
¥Route Segment Config
opengraph-image 和 twitter-image 是专门的 路由处理程序,可以使用与页面和布局相同的 路由段配置 选项。
¥opengraph-image and twitter-image are specialized Route Handlers that can use the same route segment configuration options as Pages and Layouts.
示例 
¥Examples
使用外部数据 
¥Using external data
此示例使用 params 对象和外部数据来生成图片。
¥This example uses the params object and external data to generate the image.
需要了解:默认情况下,生成的图片将为 静态优化。你可以配置单独的
fetchoptions或路由段 options 来更改此行为。¥Good to know: By default, this generated image will be statically optimized. You can configure the individual
fetchoptionsor route segments options to change this behavior.
tsx
import { ImageResponse } from 'next/og'
export const alt = 'About Acme'
export const size = {
  width: 1200,
  height: 630,
}
export const contentType = 'image/png'
export default async function Image({ params }: { params: { slug: string } }) {
  const post = await fetch(`https://.../posts/${params.slug}`).then((res) =>
    res.json()
  )
  return new ImageResponse(
    (
      <div
        style={{
          fontSize: 48,
          background: 'white',
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {post.title}
      </div>
    ),
    {
      ...size,
    }
  )
}将 Node.js 运行时与本地资源结合使用 
¥Using Node.js runtime with local assets
这些示例使用 Node.js 运行时从文件系统获取本地图片,并将其传递给 <img> src 属性(以 base64 字符串或 ArrayBuffer 格式)。将本地资源放置在相对于项目根目录的位置,而不是示例源文件的位置。
¥These examples use the Node.js runtime to fetch a local image from the file system and pass it to the <img> src attribute, either as a base64 string or an ArrayBuffer. Place the local asset relative to the project root, not the example source file.
tsx
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
export default async function Image() {
  const logoData = await readFile(join(process.cwd(), 'logo.png'), 'base64')
  const logoSrc = `data:image/png;base64,${logoData}`
  return new ImageResponse(
    (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <img src={logoSrc} height="100" />
      </div>
    )
  )
}将 ArrayBuffer 传递给 <img> 元素的 src 属性不属于 HTML 规范。next/og 使用的渲染引擎支持它,但由于 TypeScript 定义遵循规范,因此你需要 @ts-expect-error 指令或类似指令才能使用此 feature。
¥Passing an ArrayBuffer to the src attribute of an <img> element is not part of the HTML spec. The rendering engine used by next/og supports it, but because TypeScript definitions follow the spec, you need a @ts-expect-error directive or similar to use this feature.
tsx
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'
export default async function Image() {
  const logoData = await readFile(join(process.cwd(), 'logo.png'))
  const logoSrc = Uint8Array.from(logoData).buffer
  return new ImageResponse(
    (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {/* @ts-expect-error Satori accepts ArrayBuffer/typed arrays for <img src> at runtime */}
        <img src={logoSrc} height="100" />
      </div>
    )
  )
}版本历史 
¥Version History
| 版本 | 更改 | 
|---|---|
v13.3.0 | 引入了 opengraph-image 和 twitter-image。 |