# 图片生成

云开发 AI 提供基于混元大模型的文生图能力,通过文本描述即可生成高质量图片。

注意: 图片生成仅支持服务端调用(云函数),小程序端需通过 wx.cloud.callFunction() 调用云函数中转,不能直接在小程序端调用。

# 支持的模型

模型名称 说明
hunyuan-image-v3.0-v1.0.4 混元文生图 v3.0,支持自定义尺寸、prompt 改写、thinking 模式

# 支持的尺寸

尺寸 比例 说明
1024x1024 1:1 正方形(默认)
1280x720 16:9 横向宽屏
720x1280 9:16 纵向竖屏
1280x1280 1:1 正方形(大尺寸)

# 参数说明

参数 类型 必填 说明
model string 模型名称,使用 hunyuan-image-v3.0-v1.0.4
prompt string 图片描述文本,最多 500 字
size string 图片尺寸,默认 1024x1024,可选值见上表
revise { value: boolean } 是否开启 prompt 改写,开启后模型会自动优化提示词以提升生图效果
enable_thinking { value: boolean } 是否开启 thinking 模式,开启后生图质量更高但耗时更长(约增加 60 秒)

# 使用方式

# 第 1 步:创建云函数

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

// 云函数 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", "1280x1280"];

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: "hunyuan-image-v3.0-v1.0.4",
        prompt,
        size,
        revise: {value: true},
        enable_thinking: {value: false},
    });

    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 步:在小程序中调用

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:


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

# 保存图片到云存储

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

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: "hunyuan-image-v3.0-v1.0.4",
        prompt,
        revise: {value: true},
        enable_thinking: {value: false},
    });

    // 下载图片并上传到云存储
    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);
        });
    });
}

# 使用限制

  • 图片生成仅支持服务端调用(云函数),小程序端需通过 wx.cloud.callFunction() 中转
  • 生成的图片 URL 24 小时后失效,如需永久保存请上传至云存储
  • prompt 最长 500 字
  • 建议将云函数超时时间设置为 900 秒

# 提升生图质量

  • 开启 revise:让模型优化你的 prompt,通常能显著提升效果
  • 开启 enable_thinking:让模型进行更深入的理解(耗时更长,约增加 60 秒)
  • 编写详细的 prompt:包含风格、色调、构图、光线等具体描述