ImageResponse
ImageResponse 构造函数允许您使用 JSX 和 CSS 生成动态图像。这对于生成社交媒体图像(如 Open Graph 图像、Twitter 卡片等)非常有用。
参考
参数
ImageResponse 支持以下参数:
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
 
    // Options that will be passed to the HTTP response
    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)将不起作用。
- 最大捆绑包大小为 500KB。捆绑包大小包括您的 JSX、CSS、字体、图像和任何其他资产。如果超出限制,请考虑减小任何资产的大小或在运行时获取。
- 仅支持 ttf、otf和woff字体格式。为了最大限度地提高字体解析速度,ttf或otf优于woff。
示例
路由处理程序
ImageResponse 可用于路由处理程序,以便在请求时动态生成图像。
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'
 
// Image metadata
export const alt = 'My site'
export const size = {
  width: 1200,
  height: 630,
}
 
export const contentType = 'image/png'
 
// Image generation
export default async function Image() {
  return new ImageResponse(
    (
      // ImageResponse JSX element
      <div
        style={{
          fontSize: 128,
          background: 'white',
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        My site
      </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 数组,在 ImageResponse 中使用自定义字体。
app/opengraph-image.tsx
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
 
// Image metadata
export const alt = 'My site'
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 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,
        },
      ],
    }
  )
}版本历史
| 版本 | 更改 | 
|---|---|
| v14.0.0 | ImageResponse已从next/server移动到next/og。 | 
| v13.3.0 | ImageResponse可以从next/server导入。 | 
| v13.0.0 | ImageResponse通过@vercel/og包引入。 | 
这有帮助吗?