opengraph 图片和 twitter 图片
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-image
file size must not exceed 5MB, and theopengraph-image
file 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.
<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.
<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.
About Acme
<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.
About Acme
<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.js
andtwitter-image.js
are 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
.
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
// 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
const interSemiBold = fetch(
new URL('./Inter-SemiBold.ttf', import.meta.url)
).then((res) => res.arrayBuffer())
return new ImageResponse(
(
// ImageResponse JSX element
<div
>
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: await interSemiBold,
style: 'normal',
weight: 400,
},
],
}
)
}
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
// 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
const interSemiBold = fetch(
new URL('./Inter-SemiBold.ttf', import.meta.url)
).then((res) => res.arrayBuffer())
return new ImageResponse(
(
// ImageResponse JSX element
<div
>
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: await interSemiBold,
style: 'normal',
weight: 400,
},
],
}
)
}
<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.
export default function Image({ params }: { params: { slug: string } }) {
// ...
}
export default function Image({ params }) {
// ...
}
路由 | 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' } |
app/shop/[...slug]/opengraph-image.js | /shop/1/2 | { slug: ['1', '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:
ImageResponse
satisfies 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
export const alt = 'My images alt text'
export default function Image() {}
export const alt = 'My images alt text'
export default function Image() {}
<meta property="og:image:alt" content="My images alt text" />
size
export const size = { width: 1200, height: 630 }
export default function Image() {}
export const size = { width: 1200, height: 630 }
export default function Image() {}
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
contentType
export const contentType = 'image/png'
export default function Image() {}
export const contentType = 'image/png'
export default function Image() {}
<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.
很高兴知道:默认情况下,生成的图片将为 静态优化。你可以配置单独的
fetch
options
或路由段 options 来更改此行为。¥Good to know: By default, this generated image will be statically optimized. You can configure the individual
fetch
options
or route segments options to change this behavior.
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
>
{post.title}
</div>
),
{
...size,
}
)
}
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 }) {
const post = await fetch(`https://.../posts/${params.slug}`).then((res) =>
res.json()
)
return new ImageResponse(
(
<div
>
{post.title}
</div>
),
{
...size,
}
)
}
将 Edge 运行时与本地资源结合使用
¥Using Edge runtime with local assets
此示例使用 Edge 运行时获取文件系统上的本地图片,并将其作为 ArrayBuffer
传递到 <img>
元素的 src
属性。本地资源应相对于示例源文件位置放置。
¥This example uses the Edge runtime to fetch a local image on the file system and passes it as an ArrayBuffer
to the src
attribute of an <img>
element. The local asset should be placed relative to the example source file location.
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
export default async function Image() {
const logoSrc = await fetch(new URL('./logo.png', import.meta.url)).then(
(res) => res.arrayBuffer()
)
return new ImageResponse(
(
<div
>
<img src={logoSrc} height="100" />
</div>
)
)
}
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
export default async function Image() {
const logoSrc = await fetch(new URL('./logo.png', import.meta.url)).then(
(res) => res.arrayBuffer()
)
return new ImageResponse(
(
<div
>
<img src={logoSrc} height="100" />
</div>
)
)
}
将 Node.js 运行时与本地资源结合使用
¥Using Node.js runtime with local assets
此示例使用 Node.js 运行时来获取文件系统上的本地图片,并将其作为 ArrayBuffer
传递给 <img>
元素的 src
属性。本地资源应相对于项目的根目录放置,而不是相对于示例源文件的位置。
¥This example uses the Node.js runtime to fetch a local image on the file system and passes it as an ArrayBuffer
to the src
attribute of an <img>
element. The local asset should be placed relative to the root of your project, rather than the location of the example source file.
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
>
<img src={logoSrc} height="100" />
</div>
)
)
}
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
>
<img src={logoSrc} height="100" />
</div>
)
)
}
版本历史
¥Version History
版本 | 变化 |
---|---|
v13.3.0 | 推出 opengraph-image 和 twitter-image 。 |