Làm thế nào để sử dụng Z-Image API trên PoYo: hướng dẫn phát triển hoàn chỉnh
Tìm hiểu cách tích hợp Z-Image API vào ứng dụng của bạn. Hướng dẫn từng bước với các ví dụ mã trong JavaScript, Python và cURL cho việc tạo hình ảnh AI siêu nhanh.


2026 cập nhật: Z-Image API trên PoYo chi phí 2 tín dụng cho mỗi lần tạo, khoảng $0.01. Được trang bị bởi kiến trúc S3-DiT của Alibaba, nó cung cấp việc tạo hình ảnh nhanh cho các dòng công việc sản xuất nhẹ, và hướng dẫn này hướng dẫn bạn thông qua việc tích hợp nó với PoYo của API.
Bắt đầu với Z-Image API
Bước 1: Thiết lập tài khoản PoYo của bạn
Đầu tiên, tạo tài khoản PoYo của bạn và lấy giấy chứng nhận API của bạn:
- Đăng ký tại PoYo.ai
- Tạo khóa API của bạn trong bảng điều khiển
- Thêm tín dụng cho tài khoản của bạn (Z-Image chi phí 2 tín dụng cho mỗi lần tạo)
Bước 2: Lắp đặt các phụ thuộc cần thiết
# For Node.js/JavaScript
npm install axios
# For Python
pip install requests
# For cURL (no installation needed)
Tạo ra văn bản hình ảnh cơ bản
JavaScript/Node.js Thực hiện
const axios = require('axios');
const generateImage = async (prompt, size = '1:1') => {
try {
const response = await axios.post(
'https://api.poyo.ai/api/generate/submit',
{
model: 'z-image',
callback_url: 'https://your-domain.com/callback', // Optional webhook
input: {
prompt: prompt,
size: size // Options: '1:1', '4:3', '3:4', '16:9', '9:16'
}
},
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`,
'Content-Type': 'application/json'
}
}
);
console.log('Task ID:', response.data.data.task_id);
console.log('Status:', response.data.data.status);
console.log('Created:', response.data.data.created_time);
return response.data.data;
} catch (error) {
console.error('Error generating image:', error.response?.data || error.message);
}
};
// Example usage
generateImage('A futuristic city skyline at sunset with flying cars', '16:9');
Thực hiện Python
import requests
import json
def generate_image(prompt, api_key, size='1:1'):
url = "https://api.poyo.ai/api/generate/submit"
payload = {
"model": "z-image",
"callback_url": "https://your-domain.com/callback", # Optional webhook
"input": {
"prompt": prompt,
"size": size # Options: '1:1', '4:3', '3:4', '16:9', '9:16'
}
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
result = response.json()
print(f"Task ID: {result['data']['task_id']}")
print(f"Status: {result['data']['status']}")
print(f"Created: {result['data']['created_time']}")
return result['data']
except requests.exceptions.RequestException as e:
print(f"Error generating image: {e}")
return None
# Example usage
api_key = "YOUR_API_KEY"
result = generate_image("A serene mountain landscape with crystal clear lake", api_key, '16:9')
Thực hiện cURL
curl -X POST "https://api.poyo.ai/api/generate/submit" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "z-image",
"callback_url": "https://your-domain.com/callback",
"input": {
"prompt": "A professional headshot of a confident business woman in modern office setting",
"size": "1:1"
}
}'
Các tham số API
Cơ quan yêu cầu
| Parameter | Loại | Cần | Mô tả |
|---|---|---|---|
model |
chuỗi | Vâng. | Chắc là vậy. "z-image" |
callback_url |
chuỗi | Không. | Webhook URL cho các thông báo bất đồng bộ |
input.prompt |
chuỗi | Vâng. | Mô tả văn bản (tối đa là 1000 ký tự) |
input.size |
chuỗi | Vâng. | Tỷ lệ quan điểm: 1:1, 4:3, 3:4, 16:9, 9:16 |
Phương thức phản ứng
{
"code": 200,
"data": {
"task_id": "task-unified-1757165031-uyujaw3d",
"status": "not_started",
"created_time": "2026-06-12T10:30:00"
}
}
Hướng dẫn tỷ lệ khía cạnh
Chọn kích thước phù hợp cho trường hợp sử dụng của bạn:
const sizeGuide = {
'1:1': 'Square - Social media posts, profile images, thumbnails',
'4:3': 'Landscape - Presentations, web content, traditional photos',
'3:4': 'Portrait - Mobile content, portrait photography',
'16:9': 'Widescreen - Video thumbnails, banners, hero images',
'9:16': 'Vertical - Stories, reels, mobile-first content'
};
// Generate images for different platforms
const generateForPlatform = async (prompt, platform) => {
const platformSizes = {
instagram_post: '1:1',
instagram_story: '9:16',
youtube_thumbnail: '16:9',
twitter_header: '16:9',
linkedin_post: '4:3'
};
return generateImage(prompt, platformSizes[platform]);
};
Kết quả xử lý với Webhooks
Z-Image API sử dụng webhooks để phân phối kết quả. Thiết lập điểm cuối webhook để nhận kết quả:
Thiết lập Endpoint Webhook
// Express.js webhook handler
const express = require('express');
const app = express();
app.use(express.json());
// Webhook endpoint to receive results
app.post('/webhook/callback', (req, res) => {
const { task_id, status, files } = req.body;
console.log(`Task ${task_id} status: ${status}`);
if (status === 'finished' && files && files.length > 0) {
console.log('Generated image URL:', files[0].file_url);
// Process the completed image
processGeneratedImage(task_id, files[0].file_url);
} else if (status === 'failed') {
console.error('Generation failed for task:', task_id);
handleGenerationError(task_id);
}
res.status(200).send('OK');
});
const processGeneratedImage = (taskId, imageUrl) => {
// Your logic to handle the completed image
console.log(`Processing image from task ${taskId}: ${imageUrl}`);
};
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
Thay thế: Kiểm tra tình trạng bằng tay
Nếu bạn không muốn sử dụng webhooks, bạn có thể khảo sát tình trạng nhiệm vụ:
const checkTaskStatus = async (taskId) => {
try {
const response = await axios.get(
`https://api.poyo.ai/api/generate/status/${taskId}`,
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`
}
}
);
return response.data.data;
} catch (error) {
console.error('Error checking status:', error.message);
return null;
}
};
const pollForResult = async (taskId, maxAttempts = 30) => {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const taskData = await checkTaskStatus(taskId);
if (!taskData) break;
console.log(`Status: ${taskData.status}`);
if (taskData.status === 'finished') {
console.log('Image generated successfully!');
if (taskData.files && taskData.files.length > 0) {
console.log('Image URL:', taskData.files[0].file_url);
}
return taskData;
} else if (taskData.status === 'failed') {
console.error('Generation failed:', taskData.error_message);
return null;
}
// Wait 1 second (Z-Image is fast!)
await new Promise(resolve => setTimeout(resolve, 1000));
}
console.error('Maximum polling attempts reached');
return null;
};
// Complete workflow example
const completeGeneration = async (prompt, size = '1:1') => {
// Step 1: Submit generation request
const generation = await generateImage(prompt, size);
if (!generation) return null;
// Step 2: Poll for results
const result = await pollForResult(generation.task_id);
return result;
};
Python Kiểm tra tình trạng
import time
def check_task_status(task_id, api_key):
url = f"https://api.poyo.ai/api/generate/status/{task_id}"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()['data']
except requests.exceptions.RequestException as e:
print(f"Error checking status: {e}")
return None
def wait_for_completion(task_id, api_key, max_attempts=30):
for attempt in range(max_attempts):
task_data = check_task_status(task_id, api_key)
if not task_data:
break
print(f"Status: {task_data['status']}")
if task_data['status'] == 'finished':
print("Image generated successfully!")
if task_data.get('files') and len(task_data['files']) > 0:
print(f"Image URL: {task_data['files'][0]['file_url']}")
return task_data
elif task_data['status'] == 'failed':
print(f"Generation failed: {task_data.get('error_message', 'Unknown error')}")
return None
time.sleep(1) # Wait 1 second
print("Maximum attempts reached")
return None
# Complete workflow
def complete_image_generation(prompt, api_key, size='1:1'):
# Step 1: Submit request
task_result = generate_image(prompt, api_key, size)
if not task_result:
return None
# Step 2: Wait for completion
final_result = wait_for_completion(task_result['task_id'], api_key)
return final_result
Việc xử lý lỗi và các thực hành tốt nhất
Việc xử lý lỗi toàn diện
const robustImageGeneration = async (prompt, size = '1:1', retries = 3) => {
for (let attempt = 0; attempt < retries; attempt++) {
try {
const response = await axios.post(
'https://api.poyo.ai/api/generate/submit',
{
model: 'z-image',
input: {
prompt: prompt,
size: size
}
},
{
headers: {
'Authorization': `Bearer YOUR_API_KEY`,
'Content-Type': 'application/json'
},
timeout: 30000 // 30 second timeout
}
);
return response.data.data;
} catch (error) {
if (error.response) {
const status = error.response.status;
const message = error.response.data?.error || 'Unknown error';
console.error(`API Error (${status}): ${message}`);
// Don't retry for certain errors
if (status === 401 || status === 403) {
throw new Error('Authentication failed. Check your API key.');
}
if (status === 400) {
throw new Error(`Bad request: ${message}`);
}
} else if (error.request) {
console.error('Network error:', error.message);
} else {
console.error('Request setup error:', error.message);
}
// If this was the last attempt, throw the error
if (attempt === retries - 1) {
throw error;
}
// Wait before retrying (exponential backoff)
const delay = Math.pow(2, attempt) * 1000;
console.log(`Retrying in ${delay}ms... (Attempt ${attempt + 1}/${retries})`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
};
Các hoạt động tốt nhất
- Giữ các lệnh dưới các ký tự 1000 - Z-Image có chiều dài nhanh tối đa
- Sử dụng các prompt mô tả - Các chi tiết hơn thường mang lại kết quả tốt hơn
- Kết quả cache - Tài hình ảnh được tạo để tránh tái tạo nội dung giống hệt nhau
- Chống lại bất đồng bộ đúng cách - Đợi đến khi hoàn thành nhiệm vụ trước khi sử dụng kết quả
Những lời khuyên kỹ thuật prompt
Cơ cấu nhanh hiệu quả
// Good prompts for Z-Image
const goodPrompts = [
// Clear subject + style + details
"Professional product photo of a sleek smartphone on white background, studio lighting, 4K quality",
// Scene + atmosphere + composition
"Cozy coffee shop interior at golden hour, warm lighting, wooden furniture, plants on shelves",
// Character + action + setting
"Young woman reading a book in a modern library, natural light from large windows, peaceful atmosphere",
// Text rendering (Z-Image excels at this)
"Minimalist poster design with text 'INNOVATION 2026' in bold typography, blue gradient background"
];
// Prompts optimized for bilingual text
const textPrompts = [
"Store sign with 'OPEN' in English and '营业中' in Chinese, neon style",
"Business card design with company name 'TechFlow 科技流' in elegant font"
];
Phân biến hàng loạt
const generateBatch = async (prompts, size = '1:1') => {
// Submit all generation requests in parallel
const generations = await Promise.all(
prompts.map(prompt => generateImage(prompt, size))
);
// Wait for all results
const results = await Promise.all(
generations
.filter(gen => gen !== null)
.map(gen => pollForResult(gen.task_id))
);
return results.filter(result => result !== null);
};
// Example: Generate multiple social media images
const socialMediaPrompts = [
"Motivational quote background with sunrise",
"Abstract geometric pattern in blue and purple",
"Minimalist workspace setup with laptop"
];
const images = await generateBatch(socialMediaPrompts, '1:1');
Kết luận
Z-Image API trên PoYo cung cấp việc tạo hình ảnh siêu nhanh, chất lượng cao với khả năng hiển thị văn bản hai ngôn ngữ đặc biệt. Với hai tham số đơn giản của nó API (quá trình và kích thước), bạn có thể tích hợp việc tạo hình ảnh mạnh mẽ vào các ứng dụng của bạn trong vài phút.
Để biết các tính năng tiên tiến hơn và tài liệu API đầy đủ, hãy truy cập Văn bản Z-Image API.
Sẵn sàng để bắt đầu xây dựng? Nhận khóa API của bạn và bắt đầu tạo ra với Z-Image hôm nay.
Bạn cần giúp đỡ với việc thực hiện? cộng đồng nhà phát triển hoặc xem thêm Các hướng dẫn API cho các kỹ thuật tiên tiến.

