tencent cloud

ドキュメントMedia Processing Service

AI Image Generation

ダウンロード
フォーカスモード
フォントサイズ
最終更新日: 2026-11-11 20:08:29
AI翻訳

Feature Introduction

Tencent Cloud Media Processing Service (MPS) AIGC aggregation platform provides text-to-image and image-to-image (including reference image editing) capabilities. It has aggregated mainstream image generation models such as Kling, Vidu, Hunyuan, and Wan, allowing developers to call different models through a unified set of APIs.

Note:
For detailed information about the aggregated image generation models, see the ModelName and ModelVersion parameters in Create AIGC Image Task.

Billing Overview

When you use MPS to call AI image generation, the number of images in successfully generated task results is counted, and the billing unit is per image. For complete descriptions of billing rules for each type, see the Pay-as-you-go documentation.

Prerequisites

1. Activating the Service

1. Log in to the Tencent Cloud MPS console and follow the instructions to activate the MPS service.
2. To obtain the API key, go to API Key Management to get the SecretId and SecretKey.
3. (Optional) To store the generated results in COS, you also need to activate Cloud Object Storage (COS), create a bucket, and grant permissions to the MPS_QcsRole role. For more information, see the Account Authorization documentation.

2. Installing Dependencies

The code examples in this guide use axios as the HTTP client, but it is not required. You can choose any of the following methods to send HTTP requests based on your project requirements.
Solution
Installation Required or Not
Scenario
axios (default for this document)
npm install axios
Existing projects are using axios, or you prefer its API style.
Node.js native fetch
No installation required (built into Node.js ≥ 18)
Zero dependencies, recommended for modern projects.
Node.js native https
No installation required
Compatible with older Node.js versions (< 18).
If you choose axios:
npm install axios

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)

If you choose native fetch (Node.js 18 or later, zero dependencies), replace axios.post(...) in your code with:
// Replace the axios.post call
// Original: const resp = await axios.post(`https://${MPS_HOST}`, payload, { headers });
// return resp.data;
// Change to:
const resp = await fetch(`https://${MPS_HOST}`, {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
});
return await resp.json();

Note:
The built-in crypto module in Node.js can be used to generate the signature, with no additional installation required. The signing process has no external dependencies.

3. Key Configuration

{
"tencentCloud": {
"secretId": "Your SecretId",
"secretKey": "Your SecretKey",
"region": "ap-guangzhou"
}
}
Attention:
Security reminder: Never hardcode keys in your code or commit them to Git. We recommend using environment variables or a separate configuration file (add it to .gitignore).

API Overview

API
Action
Function
Request Rate Limit
CreateAigcImageTask
Generate an image based on the prompt.
20 requests/second
DescribeAigcImageTask
Poll the image generation progress and result.
20 requests/second
Note:
General information:
Request domain: mps.intl.tencentcloudapi.com
Request method: POST (application/json)
API version: 2019-06-12
Signature method: TC3-HMAC-SHA256

Signature Mechanism (TC3-HMAC-SHA256)

TencentCloud API 3.0 uses TC3-HMAC-SHA256 signature authentication. The signing process is as follows:
1. Construct the canonical request (CanonicalRequest): concatenate the request method, URI, QueryString, Headers, and Payload Hash.
2. Construct the string to be signed (StringToSign): concatenate the algorithm, timestamp, CredentialScope, and CanonicalRequest Hash.
3. Calculate the Signature: derive the signing key step by step using HMAC with the SecretKey, and then sign the StringToSign.
4. Construct the Authorization Header: assemble the final authentication header.

Must-Knows

1. Generated results are stored for only 12 hours.
The URLs of images and videos are valid for only 12 hours. Be sure to download or transfer them to your own COS/server promptly after generation.
2. Rate limit
Image creation/query: 20 requests/second
Video creation: 10 requests/second
Video query: 50 requests/second
We recommend implementing concurrency control and request queues to avoid triggering rate limiting.
3. Image Input Requirements
A size of less than 7 MB is recommended for image generation, or less than 10 MB for video generation.
Supported formats: jpeg, png, webp.
The image URL must be publicly accessible.
4. Prompt Length Limit
Image Prompt: We recommend keeping it under 1,000 characters.
Video Prompt: We recommend keeping it under 2,000 characters.
5. COS Storage
You can use StoreCosParam to store results directly in a specified COS bucket. This requires:
Enable the COS service.
Create a bucket.
Grant the MPS_QcsRole role access to the bucket.

Core Code Implementation

1. Signature Tool (tencent-sign.js)

/**
* TencentCloud API Signature Tool (TC3-HMAC-SHA256)
*/
const crypto = require('crypto');

function sha256(message) {
return crypto.createHash('sha256').update(message).digest('hex');
}

function hmac256(key, message) {
return crypto.createHmac('sha256', key).update(message).digest();
}

/**
* Generate a TencentCloud API V3 signature.
* @param {string} secretId - Tencent Cloud SecretId
* @param {string} secretKey - Tencent Cloud SecretKey
* @param {string} service - Service name, such as 'mps'
* @param {string} action - API name, such as 'CreateAigcImageTask'
* @param {string} payload - Request body JSON string
* @param {string} region - Region, such as 'ap-guangzhou'
* @param {string} [version] - API version, default '2019-06-12'
* @returns {{ headers: object }} - Request headers containing the complete signature.
*/
function signRequest(secretId, secretKey, service, action, payload, region, version) {
const timestamp = Math.floor(Date.now() / 1000);
const date = new Date(timestamp * 1000).toISOString().split('T')[0];

// ===== Step 1: Concatenate the canonical request string =====
const httpRequestMethod = 'POST';
const canonicalUri = '/';
const canonicalQueryString = '';
const contentType = 'application/json';
const canonicalHeaders =
`content-type:${contentType}\\n` +
`host:${service}.tencentcloudapi.com\\n` +
`x-tc-action:${action.toLowerCase()}\\n`;
const signedHeaders = 'content-type;host;x-tc-action';
const hashedRequestPayload = sha256(payload);
const canonicalRequest =
`${httpRequestMethod}\\n${canonicalUri}\\n${canonicalQueryString}\\n` +
`${canonicalHeaders}\\n${signedHeaders}\\n${hashedRequestPayload}`;

// ===== Step 2: Concatenate the string to be signed =====
const algorithm = 'TC3-HMAC-SHA256';
const credentialScope = `${date}/${service}/tc3_request`;
const hashedCanonicalRequest = sha256(canonicalRequest);
const stringToSign =
`${algorithm}\\n${timestamp}\\n${credentialScope}\\n${hashedCanonicalRequest}`;

// ===== Step 3: Calculate the signature =====
const secretDate = hmac256(`TC3${secretKey}`, date);
const secretService = hmac256(secretDate, service);
const secretSigning = hmac256(secretService, 'tc3_request');
const signature = crypto.createHmac('sha256', secretSigning)
.update(stringToSign).digest('hex');

// ===== Step 4: Concatenate the Authorization header =====
const authorization =
`${algorithm} Credential=${secretId}/${credentialScope}, ` +
`SignedHeaders=${signedHeaders}, Signature=${signature}`;

return {
headers: {
'Authorization': authorization,
'Content-Type': contentType,
'Host': `${service}.tencentcloudapi.com`,
'X-TC-Action': action,
'X-TC-Timestamp': String(timestamp),
'X-TC-Version': version || '2019-06-12',
'X-TC-Region': region || ''
}
};
}

module.exports = { signRequest };

2. MPS API Wrapper (mps-api.js)

const axios = require('axios');
const { signRequest } = require('./tencent-sign');

const MPS_HOST = 'mps.tencentcloudapi.com';
const SERVICE = 'mps';

/**
* Generic MPS API call function
* @param {string} action - API Action name
* @param {object} params - Request parameters
* @param {object} config - Contains tencentCloud.secretId / secretKey / region
* @returns {object} API response
*/
async function callMpsApi(action, params, config) {
const payload = JSON.stringify(params);
const { headers } = signRequest(
config.tencentCloud.secretId,
config.tencentCloud.secretKey,
SERVICE,
action,
payload,
config.tencentCloud.region
);

const resp = await axios.post(`https://${MPS_HOST}`, payload, { headers });
return resp.data;
}

// =============================================
// Image generation
// =============================================

/**
* Create an AIGC image generation task
* @param {string} prompt - Image description (up to 1,000 characters)
* @param {string} negativePrompt - Negative prompt (optional)
* @param {object} options - Additional options
* @param {string} options.modelName - Model name. Defaults to 'Hunyuan'. Options include 'Hunyuan' / 'Qwen' / others.
* @param {string} options.modelVersion - Model version. For Hunyuan, '3.0' is available.
* @param {boolean} options.enhancePrompt - Whether to automatically optimize the prompt
* @param {Array<{Url:string}>} options.imageInfos - Array of reference images
* @param {object} options.storeCos - COS storage parameters
* @returns {{ Response: { TaskId: string, RequestId: string } }}
*/
async function createImageTask(prompt, negativePrompt, options = {}) {
const config = options._config; // Pass in the configuration object

const params = {
ModelName: options.modelName || 'Hunyuan',
ModelVersion: options.modelVersion || '3.0',
Prompt: prompt,
EnhancePrompt: options.enhancePrompt !== undefined ? options.enhancePrompt : true
};

if (negativePrompt) {
params.NegativePrompt = negativePrompt;
}

// Reference image
if (options.imageInfos && options.imageInfos.length > 0) {
params.ImageInfos = options.imageInfos.map(info => ({
Url: info.Url || info.url
}));
}

// Additional parameters (such as specifying dimensions)
if (options.additionalParameters) {
params.AdditionalParameters = typeof options.additionalParameters === 'string'
? options.additionalParameters
: JSON.stringify(options.additionalParameters);
}

// COS Storage
if (options.storeCos) {
params.StoreCosParam = options.storeCos;
}

const result = await callMpsApi('CreateAigcImageTask', params, config);
return result;
}

/**
* Query AIGC image generation tasks
* @param {string} taskId - TaskId returned during task creation
* @param {object} config - Configuration object
* @returns {{ Response: { Status: string, ImageUrls: string[], Message: string, RequestId: string } }}
* Status: 'WAIT' | 'RUN' | 'DONE' | 'FAIL'
* ImageUrls: A list of image URLs returned when the task is completed (⚠️ Images are stored for only 12 hours)
*/
async function describeImageTask(taskId, config) {
const params = { TaskId: taskId };
const result = await callMpsApi('DescribeAigcImageTask', params, config);
return result;
}
module.exports = {
callMpsApi,
createImageTask,
describeImageTask
};

Complete Usage Process

1. Generating an Image (Complete Process)

const { signRequest } = require('./tencent-sign');
const axios = require('axios');

const MPS_HOST = 'mps.tencentcloudapi.com';

// === Configuration ===
const config = {
tencentCloud: {
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
region: 'ap-guangzhou'
}
};

// === Generic Call Functions ===
async function callMpsApi(action, params) {
const payload = JSON.stringify(params);
const { headers } = signRequest(
config.tencentCloud.secretId,
config.tencentCloud.secretKey,
'mps',
action,
payload,
config.tencentCloud.region
);
const resp = await axios.post(`https://${MPS_HOST}`, payload, { headers });
return resp.data;
}

// === Main Process ===
async function generateImage() {
// Step 1: Create an image generation task
console.log('🎨 Creating image generation task...');
const createResult = await callMpsApi('CreateAigcImageTask', {
ModelName: 'Hunyuan',
ModelVersion: '3.0',
Prompt: 'A beautiful sunset over mountains, photorealistic, 4K',
EnhancePrompt: true
});

const taskId = createResult.Response.TaskId;
console.log(`✅ Task created successfully, TaskId: ${taskId}`);

// Step 2: Poll for task status
let status = 'WAIT';
let imageUrls = [];

while (status === 'WAIT' || status === 'RUN') {
await new Promise(resolve => setTimeout(resolve, 5000)); // Query every 5 seconds

const queryResult = await callMpsApi('DescribeAigcImageTask', {
TaskId: taskId
});

status = queryResult.Response.Status;
console.log(`⏳ Task status: ${status}`);

if (status === 'DONE') {
imageUrls = queryResult.Response.ImageUrls;
console.log('🎉 Image generated successfully!');
console.log('📸 Image URL:', imageUrls);
} else if (status === 'FAIL') {
console.error('❌ Generation failed:', queryResult.Response.Message);
}
}

return imageUrls;
}

generateImage().catch(console.error);

2. Production-Grade Usage with Task Queues

In real-world projects, we recommend implementing a task queue to control concurrency and avoid exceeding API rate limits.
/**
* Polling function with retry and timeout
* @param {string} taskId - Task ID
* @param {string} type - 'image' | 'video'
* @param {number} timeout - Timeout in milliseconds, defaulting to 30 minutes
* @param {number} interval - Polling interval in milliseconds, defaulting to 5000
*/
async function pollTaskResult(taskId, type = 'image', timeout = 1800000, interval = 5000) {
const action = type === 'image' ? 'DescribeAigcImageTask' : 'DescribeAigcVideoTask';
const urlField = type === 'image' ? 'ImageUrls' : 'VideoUrls';

const startTime = Date.now();

while (Date.now() - startTime < timeout) {
const result = await callMpsApi(action, { TaskId: taskId });
const resp = result.Response;

if (resp.Status === 'DONE') {
return {
success: true,
urls: resp[urlField] || [],
resolution: resp.Resolution || null
};
}

if (resp.Status === 'FAIL') {
return {
success: false,
error: resp.Message || 'Task failed'
};
}

// If the status is WAIT or RUN, keep waiting.
await new Promise(resolve => setTimeout(resolve, interval));
}

return { success: false, error: 'Polling timed out' };
}

// Usage example
async function main() {
// Create an image task
const imgTask = await callMpsApi('CreateAigcImageTask', {
ModelName: 'Hunyuan',
ModelVersion: '3.0',
Prompt: 'A dramatic scene...',
EnhancePrompt: true
});
const imgResult = await pollTaskResult(imgTask.Response.TaskId, 'image');
if (imgResult.success) {
console.log('Image:', imgResult.urls[0]);

// Use the image as the first frame to continue generating the video.
const vidTask = await callMpsApi('CreateAigcVideoTask', {
ModelName: 'Kling',
ModelVersion: '3.0',
Prompt: 'The character walks forward...',
ImageUrl: imgResult.urls[0],
Duration: 5,
ExtraParameters: { EnableAudio: true }
});

const vidResult = await pollTaskResult(vidTask.Response.TaskId, 'video');
if (vidResult.success) {
console.log('Video:', vidResult.urls[0]);
console.log('Resolution:', vidResult.resolution);
}
}
}

main().catch(console.error);

Configuration File Reference

The following is a complete configuration example that covers all configurable options for image and video generation:
{
"tencentCloud": {
"secretId": "Your SecretId",
"secretKey": "Your SecretKey",
"region": "ap-guangzhou"
},
"cosOutput": {
"bucket": "your-bucket-name-1234567890",
"region": "ap-guangzhou",
"outputDir": "/aigc-output/"
},
"mps": {
"imageGeneration": {
"enabled": true,
"modelName": "Hunyuan",
"modelVersion": "3.0"
},
"videoGeneration": {
"enabled": true,
"modelName": "Kling",
"modelVersion": "3.0",
"duration": 5,
"enableAudio": true
}
},
"concurrency": {
"maxImageTasks": 2,
"maxVideoTasks": 1,
"pollIntervalMs": 5000
}
}

FAQs

Why Does Task Creation Report the InvalidParameter.ViolationContent Error?

The prompt content triggered a content moderation block. Check whether the prompt contains prohibited content.

Why Does Task Creation Report the AuthFailure Error?

Signature verification failed. Check the following:
Whether the SecretId/SecretKey is correct.
Whether the timestamp is accurate (the local time must be synchronized with the server time).
Whether the signature algorithm implementation is correct.

Why Does Polling Keep Returning the WAIT/RUN Status?

Image generation typically takes 1 to 3 minutes, and video generation typically takes 3 to 5 minutes. We recommend setting a reasonable timeout, such as 30 minutes.

Why Does EnableAudio Not Take Effect?

The audio-video synchronization feature is supported only by specific versions of certain models, such as Kling 3.0. Confirm whether the model and version you are using support this feature.

Why Does the Duration Parameter Not Work?

Different models support different duration values (see the table above). If you pass in an unsupported value, it may be ignored or cause an error.

Appendix: HTTP Raw Request Examples

If you use other languages (Python/Go/Java), refer to the following raw HTTP request format:

Creating an Image Generation Task

POST / HTTP/1.1
Host: mps.tencentcloudapi.com
Content-Type: application/json
Authorization: TC3-HMAC-SHA256 Credential=xxx/2026-03-31/mps/tc3_request, SignedHeaders=content-type;host;x-tc-action, Signature=xxx
X-TC-Action: CreateAigcImageTask
X-TC-Version: 2019-06-12
X-TC-Timestamp: 1743436800
X-TC-Region: ap-guangzhou

{
"ModelName": "Hunyuan",
"ModelVersion": "3.0",
"Prompt": "A young woman in ancient Chinese hanfu, standing by a moonlit lake",
"EnhancePrompt": true
}

Querying Tasks

POST / HTTP/1.1
Host: mps.tencentcloudapi.com
Content-Type: application/json
X-TC-Action: DescribeAigcImageTask
X-TC-Version: 2019-06-12

{
"TaskId": "4-AigcImage-c3b145ec76xxxx94ac55b9e63be17d"
}


ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック