Semua artikel
Tutorial8 menit baca

Bagaimana Menggunakan Z-Image API pada PoYo: Panduan Pengembang Lengkap

Pelajari cara mengintegrasikan Z-Image API dalam aplikasi Anda. Panduan langkah demi langkah dengan contoh kode di JavaScript, Python, dan cURL untuk generasi gambar AI ultra cepat.

Bagaimana Menggunakan Z-Image API pada PoYo: Panduan Pengembang Lengkap
Tutorial

Bagaimana Menggunakan Z-Image API pada PoYo

2026 update: Z-Image API pada PoYo Biaya 2 kredit per generasi, sekitar $0.01. Bergerak oleh AlibabaArsitektur S3-DiT, ini memberikan generasi gambar cepat untuk alur kerja produksi ringan, dan panduan ini berjalan melalui mengintegrasikannya dengan PoYo API.

Memulai dengan Z-Image API

Langkah 1: Buatlah Anda PoYo Akun

Pertama, buatlah PoYo akun dan mendapatkan API Keterangan:

  1. Daftar di PoYo.ai
  2. Menghasilkan kunci API Anda di dalam papan pemindai
  3. Tambahkan kredit ke rekening Anda (biaya Z-Image 2 kredit per generasi)

Langkah 2: Install Dependensi yang Dibutuhkan

# For Node.js/JavaScript
npm install axios

# For Python
pip install requests

# For cURL (no installation needed)

Generasi teks-ke-gambar dasar

JavaScript/Node.js Pelaksanaan

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');

Python Pelaksanaan

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')

cURL Pelaksanaan

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"
    }
  }'

API Parameter

Badan Permintaan

Parameter Jenis Kebutuhan Deskripsi
model string Ya Pasti "z-image"
callback_url string Tidak, tidak. Webhook URL untuk pemberitahuan async
input.prompt string Ya Deskripsi teks (maksimum) 1000 karakter)
input.size string Ya Rasio aspek: 1:1, 4:3, 3:4, 16:9, 9:16

Format respons

{
  "code": 200,
  "data": {
    "task_id": "task-unified-1757165031-uyujaw3d",
    "status": "not_started",
    "created_time": "2026-06-12T10:30:00"
  }
}

Panduan Rasio Aspek

Pilih ukuran yang tepat untuk kasus penggunaan Anda:

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]);
};

Mengatasi Hasil dengan webhook

Z-Image API menggunakan webhook untuk pengiriman hasil. Mengatur sebuah webhook titik akhir untuk menerima hasil:

Mengatur Webhook Titik akhir

// 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');
});

Alternatif: Pemeriksaan Status Manual

Jika Anda lebih suka tidak menggunakan webhook, Anda dapat melakukan survei status tugas:

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 Pemeriksaan Status

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

Pengendalian Kesalahan dan Praktik Terbaik

Pengendalian Kesalahan Komprehensif

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));
    }
  }
};

Praktik Terbaik

  1. Jaga prompt di bawah 1000 karakter - Z-Image memiliki panjang templat maksimum
  2. Gunakan prompt deskriptif - Lebih detail umumnya menghasilkan hasil yang lebih baik
  3. Hasil cache - Simpan gambar yang dihasilkan untuk menghindari regenerasi konten yang sama
  4. Mengatasi async dengan benar - Selalu tunggu sampai selesai tugas sebelum menggunakan hasil

Tips Teknik prompt

Struktur Promp yang Efektif

// 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"
];

Pengolahan Batch

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');

Kesimpulan

Z-Image API pada PoYo menyediakan generasi gambar yang sangat prompt dan berkualitas tinggi dengan kemampuan rendering teks bilingual yang luar biasa. Dengan dua parameter sederhana API (prompt dan ukuran), Anda dapat mengintegrasikan generasi gambar yang kuat ke dalam aplikasi Anda dalam hitungan menit.

Untuk fitur yang lebih canggih dan lengkap Dokumentasi API, kunjungi Z-Image resmi Dokumentasi API.

Siap untuk mulai membangun? Ambillahmu kunci API dan mulai membuat dengan Z-Image hari ini.


Perlu bantuan dengan implementasi? Bergabunglah dengan kami komunitas pengembang atau lihat lebih banyak API Tutorial untuk teknik canggih.

Blog · PoYo.aiSemua artikel
HUBUNGI KAMI

Punya proyek?

Ceritakan apa yang Anda bangun. Tim kami akan membantu memilih API AI yang tepat.

Data Anda hanya digunakan untuk menanggapi pertanyaan ini.

PoYo AI

Siap menjelajahi model?

Jelajahi model gambar, video, audio, dan bahasa di PoYo.

Lihat model AI