NNext.js 中文网 GitHub

ImageResponse

ImageResponse 构造函数的 API 参考。

ImageResponse 构造函数让你可以使用 JSX 和 CSS 生成动态图片。这适用于生成 Open Graph 图片、Twitter 卡片等社交媒体图片。

参考#

参数#

ImageResponse 支持以下参数:

jsx
import { ImageResponse } from 'next/og'

new ImageResponse(
  element: ReactElement,
  options: {
    width?: number = 1200
    height?: number = 630
    emoji?: 'twemoji' | 'blobmoji' | 'noto' | 'openmoji' = 'twemoji',
    fonts?: {
      name: string,
      data: ArrayBuffer,
      weight: number,
      style: 'normal' | 'italic'
    }[]
    debug?: boolean = false

    // 将传递给 HTTP 响应的选项
    status?: number = 200
    statusText?: string
    headers?: Record<string, string>
  },
)

示例可在 Vercel OG Playground 中查看。

支持的 HTML 和 CSS 特性#

ImageResponse 支持常见的 CSS 属性,包括 flexbox、绝对定位、自定义字体、文本换行、居中和嵌套图片。

有关支持的 HTML 和 CSS 特性列表,请参阅 Satori 的文档。

行为#

  • ImageResponse 使用 @vercel/og、Satori 和 Resvg 将 HTML 和 CSS 转换为 PNG。
  • 仅支持 flexbox 和部分 CSS 属性。高级布局(例如 display: grid)将无法工作。
  • 最大 bundle 大小为 500KB。bundle 大小包括你的 JSX、CSS、字体、图片和任何其他资源。如果超出限制,请考虑减小资源体积或在运行时获取。
  • 仅支持 ttf、otf 和 woff 字体格式。为了最大化字体解析速度,优先使用 ttf 或 otf 而非 woff。

示例#

Route Handler#

ImageResponse 可用于 Route Handler,在请求时动态生成图片。

app/api/route.js
import { ImageResponse } from 'next/og'

export async function GET() {
  try {
    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'white',
            padding: '40px',
          }}
        >
          <div
            style={{
              fontSize: 60,
              fontWeight: 'bold',
              color: 'black',
              textAlign: 'center',
            }}
          >
            Welcome to My Site
          </div>
          <div
            style={{
              fontSize: 30,
              color: '#666',
              marginTop: '20px',
            }}
          >
            Generated with Next.js ImageResponse
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 630,
      }
    )
  } catch (e) {
    console.log(`${e.message}`)
    return new Response(`Failed to generate the image`, {
      status: 500,
    })
  }
}

基于文件的元数据#

可以在 opengraph-image.tsx 文件中使用 ImageResponse,在构建时或请求时动态生成 Open Graph 图片。

app/opengraph-image.tsx
import { ImageResponse } from 'next/og'

// 图片元数据
export const alt = 'My site'
export const size = {
  width: 1200,
  height: 630,
}

export const contentType = 'image/png'

// 图片生成
export default async function Image() {
  return new ImageResponse(
    (
      // ImageResponse JSX 元素
      <div
        style={{
          fontSize: 128,
          background: 'white',
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        My site
      </div>
    ),
    // ImageResponse 选项
    {
      // 为方便起见,我们可以复用导出的 opengraph-image
      // size 配置来同时设置 ImageResponse 的宽高。
      ...size,
    }
  )
}

自定义字体#

可以通过在选项中提供 fonts 数组,在 ImageResponse 中使用自定义字体。字体不依赖请求数据,因此在模块作用域读取一次即可。请参阅可预测的值。

app/opengraph-image.tsx
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'

// 图片元数据
export const alt = 'My site'
export const size = {
  width: 1200,
  height: 630,
}

export const contentType = 'image/png'

const interSemiBold = await readFile(
  join(process.cwd(), 'assets/Inter-SemiBold.ttf')
)

// 图片生成
export default async function Image() {
  return new ImageResponse(
    (
      // ...
    ),
    // ImageResponse 选项
    {
      // 为方便起见,我们可以复用导出的 opengraph-image
      // size 配置来同时设置 ImageResponse 的宽高。
      ...size,
      fonts: [
        {
          name: 'Inter',
          data: interSemiBold,
          style: 'normal',
          weight: 400,
        },
      ],
    }
  )
}

版本历史#

版本变更
v14.0.0ImageResponse 从 next/server 移至 next/og
v13.3.0可以从 next/server 导入 ImageResponse。
v13.0.0通过 @vercel/og 包引入 ImageResponse。
Next.js 中文网