# 图片生成

云开发 AI 提供基于混元大模型的文生图与图生图能力，通过文本描述（图生图另需一张垫图）即可生成高质量图片。图片生成支持小程序端与云函数端两种调用方式。

> **注意：** 小程序端从基础库 `3.17.4` 起支持直接调用，使用 `wx.cloud.extend.AI.createImageModel()`；云函数端使用 `cloud.ai().createImageModel()`。小程序端的完整参数说明见 [wx.cloud.extend.AI](/minigame/dev/wxcloud/reference-sdk-api/extend/ai/client)。

## 支持的模型

| 模型名称                          | 说明                                    | 可用状态           |
|-------------------------------|---------------------------------------|----------------|
| `HY-Image-3.0-Plus-4090-Tob-v1.0` | 混元文生图 v3.0，输入文本生成图片，支持自定义尺寸、prompt 改写 | 2026 年 12 月 1 日下线 |
| `HY-Image-v3.0-I2I-ToB-v1.0.1`    | 混元图生图 v3.0，基于垫图与文本生成图片，需传入 `image_urls` 或 `images` | 2026 年 12 月 1 日下线 |

> **模型下线预告：** `HY-Image-3.0-Plus-4090-Tob-v1.0`（文生图）与 `HY-Image-v3.0-I2I-ToB-v1.0.1`（图生图）将于 **2026 年 12 月 1 日 0 点**下线，下线后调用会报错。接替模型 `hy-image-v3.5-preview` 预计 **2026 年 11 月中旬**提供，调用方式与当前模型不同，具体改造点另行通知。请评估工作量并预留适配时间。详见[《关于混元生图 3.0 模型下线的通知》](https://docs.cloudbase.net/ai/ai-inspire-plan-image-3.0-offline)。

## 支持的尺寸

| 尺寸          | 比例   | 说明       |
|-------------|------|----------|
| `1024x1024` | 1:1  | 正方形（默认）  |
| `1280x720`  | 16:9 | 横向宽屏     |
| `720x1280`  | 9:16 | 纵向竖屏     |

宽 × 高不能超过 1024 × 1024 像素，超出会返回 400 错误。

## 参数说明

| 参数                | 类型                   | 必填 | 说明                                        |
|-------------------|----------------------|----|-------------------------------------------|
| `model`           | string               | 是  | 模型名称。文生图使用 `HY-Image-3.0-Plus-4090-Tob-v1.0`，图生图使用 `HY-Image-v3.0-I2I-ToB-v1.0.1` |
| `prompt`          | string               | 是  | 图片描述文本，最多 500 字                           |
| `size`            | string               | 否  | 图片尺寸，默认 `1024x1024`，可选值见上表                |
| `revise`          | `{ value: boolean }` | 否  | 是否开启 prompt 改写，开启后模型会自动优化提示词以提升生图效果       |
| `image_urls`      | `string[]`           | 否  | 图生图垫图图片地址列表，与 `images` 二选一。最多 1 张，单张不超过 10MB，支持 jpg、jpeg、png |
| `images`          | `string[]`           | 否  | 图生图垫图 base64 列表，与 `image_urls` 二选一。最多 1 张，单张不超过 10MB。传纯 base64 字符串，不要带 `data:image/jpeg;base64,` 前缀，否则返回 400 错误（`image validate failed`） |

## 使用方式

### 小程序端直接调用

小程序端从基础库 `3.17.4` 起支持直接调用生图模型，无需经过云函数中转：

```js
// 基础库 3.17.4 及以上
wx.cloud.init({
    env: "<你的环境ID>",
});

const imageModel = wx.cloud.extend.AI.createImageModel("hunyuan-image");
const res = await imageModel.generateImage({
    model: "HY-Image-3.0-Plus-4090-Tob-v1.0",
    prompt: "一只胖胖的橘猫坐在窗台上打盹，水彩风格，温暖色调",
    size: "1024x1024",
    revise: {value: true},
    timeout: 120000, // 生图耗时较长，超时时间需给足
});

console.log(res.data[0].url);
```

图生图只需将 `model` 换成 `HY-Image-v3.0-I2I-ToB-v1.0.1`，并通过 `image_urls`（图片地址）或 `images`（base64）传入一张垫图，其余参数不变。完整示例见 [wx.cloud.extend.AI](/minigame/dev/wxcloud/reference-sdk-api/extend/ai/client)。

### 云函数端调用

**第 1 步：创建云函数**

在云函数中使用 `wx-server-sdk` 调用生图模型：

```js
// 云函数 generateImage/index.js
const cloud = require("wx-server-sdk");

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV,
    timeout: 150000, // HTTP 请求超时 150s，覆盖默认的 ~15s
});

const ALLOWED_SIZES = ["1024x1024", "1280x720", "720x1280"];

exports.main = async (event, context) => {
    const prompt = (event.prompt || "").trim();
    if (!prompt) {
        return {error: "请输入提示词"};
    }
    if (prompt.length > 500) {
        return {error: "提示词最多 500 字"};
    }

    const size = ALLOWED_SIZES.includes(event.size) ? event.size : "1024x1024";

    const imageModel = cloud.ai().createImageModel("hunyuan-image");
    const res = await imageModel.generateImage({
        model: "HY-Image-3.0-Plus-4090-Tob-v1.0",
        prompt,
        size,
        revise: {value: true},
    });

    return {
        url: res.data[0].url, // 图片 URL，24 小时有效
        revisedPrompt: res.data[0].revised_prompt, // 优化后的提示词
    };
};
```

> 云函数的 `package.json` 中需要指定 `wx-server-sdk` 版本 ≥ **3.0.5-beta.1**。

**第 2 步：在小程序中调用**

```js
Page({
    data: {
        imageUrl: "",
        isLoading: false,
    },

    async generateImage() {
        this.setData({isLoading: true, imageUrl: ""});

        try {
            const res = await wx.cloud.callFunction({
                name: "generateImage",
                data: {
                    prompt: "一只胖胖的橘猫坐在窗台上打盹，水彩风格，温暖色调",
                    size: "1024x1024",
                },
            });

            if (res.result.error) {
                wx.showToast({title: res.result.error, icon: "none"});
                return;
            }

            this.setData({imageUrl: res.result.url});
        } catch (error) {
            console.error("生成失败:", error);
            wx.showToast({title: "生成失败", icon: "error"});
        } finally {
            this.setData({isLoading: false});
        }
    },
});
```

对应的 WXML：

```xml

<view class="container">
    <image wx:if="{{imageUrl}}" src="{{imageUrl}}" mode="aspectFit" class="result-image"/>
    <button bindtap="generateImage" disabled="{{isLoading}}">
        {{isLoading ? '生成中...' : '生成图片'}}
    </button>
</view>
```

## 保存图片到云存储

生成的图片 URL **24 小时后失效**。如需永久保存，可在云函数中直接下载并上传到云存储：

```js
const https = require("https");
const cloud = require("wx-server-sdk");

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV,
    timeout: 150000,
});

exports.main = async (event, context) => {
    const prompt = (event.prompt || "").trim();

    const imageModel = cloud.ai().createImageModel("hunyuan-image");
    const res = await imageModel.generateImage({
        model: "HY-Image-3.0-Plus-4090-Tob-v1.0",
        prompt,
        revise: {value: true},
    });

    // 下载图片并上传到云存储
    const imageBuffer = await downloadImage(res.data[0].url);
    const uploadRes = await cloud.uploadFile({
        cloudPath: `ai-images/${Date.now()}.jpg`,
        fileContent: imageBuffer,
    });

    return {
        fileID: uploadRes.fileID, // 永久有效的云存储链接
        revisedPrompt: res.data[0].revised_prompt,
    };
};

function downloadImage(url) {
    return new Promise((resolve, reject) => {
        https.get(url, (response) => {
            const chunks = [];
            response.on("data", (chunk) => chunks.push(chunk));
            response.on("end", () => resolve(Buffer.concat(chunks)));
            response.on("error", reject);
        });
    });
}
```

## 使用限制

- 小程序端直接调用需基础库 `3.17.4` 及以上；低于该版本时，需通过 `wx.cloud.callFunction()` 调用云函数中转
- 生成的图片 URL **24 小时后失效**，如需永久保存请上传至云存储
- prompt 最长 500 字
- 建议将云函数超时时间设置为 **900 秒**

## 提升生图质量

- 开启 `revise`：让模型优化你的 prompt，通常能显著提升效果
- 编写详细的 prompt：包含风格、色调、构图、光线等具体描述
