> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monad.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何在 Farcaster Mini App 中生成用户专属图片

在 Farcaster Mini App 中创建可分享的时刻是与用户互动的好方法。

您可以在 Farcaster Mini App 中生成自定义的、用户专属的可分享图片,让用户轻松分享!

<img src="https://mintcdn.com/monadfoundation-40611fb6/-TCPhWHMfGzx9j3a/static/img/templates/farcaster-miniapp/generating-custom-og-images/1.png?fit=max&auto=format&n=-TCPhWHMfGzx9j3a&q=85&s=23af840b83021b5ae591865658fbb22e" alt="Example" width="600" height="400" data-path="static/img/templates/farcaster-miniapp/generating-custom-og-images/1.png" />

在本指南中,我们设置了一个专用端点 `/api/og` 用于生成图片,并使用 `@vercel/og` 包来生成图片。

## 生成图片

如果您使用的是 [Monad Mini App 模板](https://github.com/monad-developers/monad-miniapp-template),只需编辑 [`app/api/og/route.tsx`](https://github.com/monad-developers/monad-miniapp-template/blob/main/app/api/og/route.tsx) 即可生成您想要的图片。

```ts lines title="app/api/og/route.tsx" theme={null}
...

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);

    // The below is dependent on whether the username and image are passed as query params or not.
    const username = searchParams.get('username') || 'User'; // Username of the user
    const imageUrl = searchParams.get('image') || ''; // Image url of the user
    
    const backgroundGradient = '#2D1B69'; // Background color of the image
    
    // Load Inter font from the public folder
    const interFontData = await fetch(
      `${request.nextUrl.origin}/Inter.ttf`
    ).then((res) => res.arrayBuffer());
    
    return new ImageResponse(
    (
        // Generate the image here
    );
  } catch (e) {
    console.error('Error generating OG image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}

...
```

如果您没有使用该模板,则需要安装 `@vercel/og` 包。

```bash theme={null}
npm install @vercel/og
```

如果您使用 Next.js 14 或更高版本,请创建一个新文件 `app/api/og/route.tsx`。

```ts lines title="app/api/og/route.tsx" theme={null}
import { ImageResponse } from '@vercel/og';
import { NextRequest } from 'next/server';

// Generate the image for every request
export const dynamic = "force-dynamic";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    
    // The below is dependent on whether the username and image are passed as query params or not.
    const username = searchParams.get('username') || 'User'; // Username of the user
    const imageUrl = searchParams.get('image') || ''; // Image url of the user
    
    return new ImageResponse(
    (
        // Generate the image here
    );
  } catch (e) {
    console.error('Error generating OG image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
```

如果您没有使用 Next.js,可以设置一个端点或专用微服务来生成图片。

## 通过 Mini App 分享图片

<img src="https://mintcdn.com/monadfoundation-40611fb6/-TCPhWHMfGzx9j3a/static/img/templates/farcaster-miniapp/generating-custom-og-images/2.png?fit=max&auto=format&n=-TCPhWHMfGzx9j3a&q=85&s=309ea3febb0e5a88e4dc42669e0a0ecd" alt="来自 EGGS Mini App 的示例,提示用户 cast 一张自定义生成的图片" style={{marginLeft: "auto", marginRight: "auto"}} width="600" height="400" data-path="static/img/templates/farcaster-miniapp/generating-custom-og-images/2.png" />

为您的 Mini App 添加可分享元素,让用户可以通过 Mini App 分享生成的图片。

下面是一个用于生成并分享自定义图片的按钮示例:

```tsx lines theme={null}
export default function GenerateAndShareCustomImage() {

...

    const handleGenerateCustomOGImage = () => {
        // Generate the image using the endpoint
        const ogImageUrl = `${APP_URL}/api/og?username=${username}&image=${pfpUrl}`;

        // Programmatically compose a cast with the generated image
        actions?.composeCast({
            // Text to be displayed in the cast
            text: "I generated a custom OG image using Monad Mini App template", 
            // Image to be displayed in the cast
            embeds: [ogImageUrl],
        });
    };

...

    return (
        <button
            type="button"
            className="bg-white text-black rounded-md p-2 text-sm"
            /**
             * When the button is clicked, the shareable image is generated 
             * and the cast is composed.
            */
            onClick={() => handleGenerateCustomOGImage()}
            disabled={!fid}
        >
            Generate Custom Image
        </button>
    );

}
```
