Skip to main content

Mini Program

WeChat Mini Programs call image generation models directly through wx.cloud.extend.AI.createImageModel, without a Cloud Function relay.

Prerequisites​

  • WeChat base library 3.17.4 or later
  • A CloudBase environment
  • Image generation resources: the quota included in the Mini Program Growth Plan

Initialization​

Initialize CloudBase in app.js. wx.cloud.extend.AI depends on the environment information set during initialization:

App({
onLaunch() {
wx.cloud.init({
env: "your-env-id",
});
},
});

Text-to-Image​

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: "A chubby orange cat napping on a windowsill, watercolor style, warm tones",
size: "1024x1024",
revise: { value: true },
timeout: 120000,
});

console.log(res.data[0].url); // Image URL, valid for 24 hours
console.log(res.data[0].revised_prompt); // Rewritten prompt

Image-to-Image​

HY-Image-v3.0-I2I-ToB-v1.0.1 requires one reference image, passed either as image_urls (URL list) or images (base64 list). Use only one of them. A maximum of 1 image is supported, up to 10 MB each, in jpg, jpeg, or png format.

const imageModel = wx.cloud.extend.AI.createImageModel("hunyuan-image");

const res = await imageModel.generateImage({
model: "HY-Image-v3.0-I2I-ToB-v1.0.1",
prompt: "Turn this photo into an oil painting",
size: "1024x1024",
revise: { value: true },
image_urls: ["https://example.com/reference.jpg"],
timeout: 120000,
});

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

When the user picks an image from the album, upload it to Cloud Storage first, then use its temporary URL as the reference image:

Page({
async pickAndGenerate() {
const { tempFiles } = await wx.chooseMedia({
count: 1,
mediaType: ["image"],
});

const { fileID } = await wx.cloud.uploadFile({
cloudPath: `ai-input/${Date.now()}.jpg`,
filePath: tempFiles[0].tempFilePath,
});

const { fileList } = await wx.cloud.getTempFileURL({ fileList: [fileID] });

const imageModel = wx.cloud.extend.AI.createImageModel("hunyuan-image");
const res = await imageModel.generateImage({
model: "HY-Image-v3.0-I2I-ToB-v1.0.1",
prompt: "Turn this photo into an oil painting",
image_urls: [fileList[0].tempFileURL],
revise: { value: true },
timeout: 120000,
});

this.setData({ imageUrl: res.data[0].url });
},
});

Parameters​

AI.createImageModel​

function createImageModel(provider: string): ImageModel;
ParameterTypeRequiredDescription
providerstringYesModel provider name, always "hunyuan-image"

ImageModel.generateImage​

function generateImage(data: GenerateImageInput): Promise<GenerateImageOutput>;

interface GenerateImageInput {
model: string;
prompt: string;
size?: string;
revise?: { value: boolean };
footnote?: string;
image_urls?: string[];
images?: string[];
timeout?: number;
}

interface GenerateImageOutput {
id: string;
created: number;
data: Array<{
url: string;
revised_prompt?: string;
}>;
}
ParameterTypeRequiredDescription
modelstringYesHY-Image-3.0-Plus-4090-Tob-v1.0 for text-to-image, HY-Image-v3.0-I2I-ToB-v1.0.1 for image-to-image
promptstringYesImage description, max 500 characters
sizestringNoDefaults to 1024x1024. Options: 1024x1024, 1280x720, 720x1280, 1280x1280
revise{ value: boolean }NoWhether to rewrite the prompt. When enabled, the model optimizes the prompt automatically
footnotestringNoWatermark text
image_urlsstring[]NoReference image URL list, alternative to images
imagesstring[]NoReference image base64 list, alternative to image_urls
timeoutnumberNoRequest timeout in milliseconds. 120000 is recommended

The returned data is a list of images. Each item contains url (valid for 24 hours) and revised_prompt (returned when revise is enabled).

Full Example​

A working generation page with loading state and error handling:

Page({
data: {
prompt: "",
imageUrl: "",
revisedPrompt: "",
loading: false,
},

onInput(e) {
this.setData({ prompt: e.detail.value });
},

async generate() {
const prompt = this.data.prompt.trim();
if (!prompt || this.data.loading) return;
if (prompt.length > 500) {
wx.showToast({ title: "Prompt must be 500 characters or fewer", icon: "none" });
return;
}

this.setData({ loading: true, imageUrl: "", revisedPrompt: "" });

try {
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,
});

this.setData({
imageUrl: res.data[0].url,
revisedPrompt: res.data[0].revised_prompt || "",
});
} catch (err) {
console.error("Image generation failed", err);
wx.showToast({ title: "Generation failed, please retry", icon: "error" });
} finally {
this.setData({ loading: false });
}
},
});
<view class="page">
<textarea bindinput="onInput" placeholder="Describe the image you want" maxlength="500" />
<button bindtap="generate" loading="{{loading}}" disabled="{{loading}}">
{{loading ? "Generating…" : "Generate"}}
</button>
<image wx:if="{{imageUrl}}" src="{{imageUrl}}" mode="widthFix" />
<text wx:if="{{revisedPrompt}}">Rewritten prompt: {{revisedPrompt}}</text>
</view>

Save Images to Cloud Storage​

Generated image URLs expire after 24 hours. To keep an image, download it to a local temporary file and upload it to Cloud Storage:

async function saveToCloudStorage(url) {
const { tempFilePath } = await wx.downloadFile({ url });

const { fileID } = await wx.cloud.uploadFile({
cloudPath: `ai-images/${Date.now()}.jpg`,
filePath: tempFilePath,
});

return fileID;
}

⚠️ wx.downloadFile is subject to the downloadFile domain allowlist. Add the image domain in the Mini Program console before release. Displaying a network image with the <image> component is not subject to this restriction.

Compared with Cloud Function Calls​

AspectMini Program clientCloud Function (wx-server-sdk)
Entry pointwx.cloud.extend.AI.createImageModelcloud.ai().createImageModel
Base library / dependencyBase library ≥ 3.17.4, nothing to installwx-server-sdk ≥ 4.0.2
Timeout controltimeout parameter (milliseconds)Cloud Function timeout
API key exposureNone, authenticated by login sessionNone, server-side call
Best forDirect generation inside the Mini ProgramPersisting results, batch processing, cross-client reuse