> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pictory.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate Image from Text Prompt

> Create AI-generated images from descriptive text prompts using the Pictory AI Studio API

This guide walks you through generating an AI image from a text prompt using the Pictory AI Studio API. You will learn how to submit a prompt, select a model and style, and retrieve the generated image by polling the job status.

## What You Will Build

<CardGroup cols={2}>
  <Card title="Text to Image" icon="wand-magic-sparkles">
    Generate images from descriptive text prompts
  </Card>

  <Card title="Model Selection" icon="microchip">
    Choose from multiple AI image models
  </Card>

  <Card title="Style Control" icon="palette">
    Apply visual styles such as photorealistic, artistic, or cartoon
  </Card>

  <Card title="Job Polling" icon="clock">
    Monitor image generation and retrieve the result
  </Card>
</CardGroup>

## Before You Begin

Make sure you have:

* A Pictory API key ([get one here](https://app.pictory.ai/api-access))
* Node.js or Python installed on your machine
* The required packages installed

<CodeGroup>
  ```bash npm theme={null}
  npm install axios
  ```

  ```bash pip theme={null}
  pip install requests
  ```
</CodeGroup>

## Step-by-Step Guide

### Step 1: Set Up Your Request

Prepare your API credentials and define the image prompt along with the desired model and style.

<CodeGroup>
  ```javascript Node.js theme={null}
  import axios from "axios";

  const API_BASE_URL = "https://api.pictory.ai/pictoryapis";
  const API_KEY = "YOUR_API_KEY"; // Replace with your actual API key

  // Image generation configuration
  const imageRequest = {
    prompt: "A golden retriever running through a sunlit meadow with wildflowers in the background",
    model: "seedream3.0",
    aspectRatio: "16:9",
    style: "photorealistic"
  };
  ```

  ```python Python theme={null}
  import requests
  import time

  API_BASE_URL = "https://api.pictory.ai/pictoryapis"
  API_KEY = "YOUR_API_KEY"  # Replace with your actual API key

  # Image generation configuration
  image_request = {
      "prompt": "A golden retriever running through a sunlit meadow with wildflowers in the background",
      "model": "seedream3.0",
      "aspectRatio": "16:9",
      "style": "photorealistic"
  }
  ```
</CodeGroup>

### Step 2: Submit the Image Generation Request

Send the request to the AI Studio image generation endpoint. On success, the API returns a `jobId` that you will use to poll for the result.

<CodeGroup>
  ```javascript Node.js theme={null}
  async function generateImage() {
    try {
      console.log("Submitting image generation request...");

      const response = await axios.post(
        `${API_BASE_URL}/v1/aistudio/images`,
        imageRequest,
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: API_KEY,
          },
        }
      );

      const jobId = response.data.data.jobId;
      console.log("Image generation started.");
      console.log("Job ID:", jobId);

      return jobId;
    } catch (error) {
      console.error("Error submitting request:", error.response?.data || error.message);
      throw error;
    }
  }
  ```

  ```python Python theme={null}
  def generate_image():
      try:
          print("Submitting image generation request...")

          response = requests.post(
              f"{API_BASE_URL}/v1/aistudio/images",
              json=image_request,
              headers={
                  "Content-Type": "application/json",
                  "Authorization": API_KEY
              }
          )
          response.raise_for_status()

          job_id = response.json()["data"]["jobId"]
          print("Image generation started.")
          print(f"Job ID: {job_id}")

          return job_id

      except requests.exceptions.RequestException as error:
          print(f"Error submitting request: {error}")
          raise
  ```
</CodeGroup>

### Step 3: Poll for the Result

Check the job status at regular intervals until the image is ready. The recommended polling interval is 10 to 30 seconds.

<CodeGroup>
  ```javascript Node.js theme={null}
  async function waitForImage(jobId) {
    console.log("\nPolling for image generation result...");

    while (true) {
      const response = await axios.get(
        `${API_BASE_URL}/v1/jobs/${jobId}`,
        {
          headers: { Authorization: API_KEY },
        }
      );

      const data = response.data;
      const status = data.data.status;
      console.log("Status:", status);

      if (status === "completed") {
        console.log("\nImage generated successfully!");
        console.log("Image URL:", data.data.url);
        console.log("Dimensions:", data.data.width, "x", data.data.height);
        console.log("AI Credits Used:", data.data.aiCreditsUsed);
        return data;
      }

      if (status === "failed") {
        throw new Error("Image generation failed: " + JSON.stringify(data));
      }

      // Wait 15 seconds before polling again
      await new Promise(resolve => setTimeout(resolve, 15000));
    }
  }

  // Run the complete workflow
  generateImage()
    .then(jobId => waitForImage(jobId))
    .then(result => console.log("\nDone!"))
    .catch(error => console.error("Error:", error));
  ```

  ```python Python theme={null}
  def wait_for_image(job_id):
      print("\nPolling for image generation result...")

      while True:
          response = requests.get(
              f"{API_BASE_URL}/v1/jobs/{job_id}",
              headers={"Authorization": API_KEY}
          )
          response.raise_for_status()

          data = response.json()
          status = data["data"]["status"]
          print(f"Status: {status}")

          if status == "completed":
              print("\nImage generated successfully!")
              print(f"Image URL: {data['data']['url']}")
              print(f"Dimensions: {data['data']['width']} x {data['data']['height']}")
              print(f"AI Credits Used: {data['data']['aiCreditsUsed']}")
              return data

          if status == "failed":
              raise Exception(f"Image generation failed: {data}")

          # Wait 15 seconds before polling again
          time.sleep(15)

  # Run the complete workflow
  if __name__ == "__main__":
      job_id = generate_image()
      result = wait_for_image(job_id)
      print("\nDone!")
  ```
</CodeGroup>

## Understanding the Parameters

| Parameter           | Type   | Required | Default                                     | Description                                                                                                                                                                                                                |
| ------------------- | ------ | -------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt`            | string | Yes      | —                                           | A descriptive text of the image to generate. Must be between 5 and 5,000 characters.                                                                                                                                       |
| `model`             | string | No       | `seedream3.0`                               | The AI model to use for generation. Supported values: `seedream3.0`, `flux-schnell`, `nanobanana`, `nanobanana-pro`. See [Generate Image API](/api-reference/ai-studio/generate-image) for model capabilities and pricing. |
| `aspectRatio`       | string | No       | First supported ratio of the selected model | The output aspect ratio. Valid values depend on the selected model (e.g., `1:1`, `16:9`, `9:16`).                                                                                                                          |
| `style`             | string | No       | —                                           | Visual style to apply to the generated image. Supported values: `photorealistic`, `artistic`, `cartoon`, `minimalist`, `vintage`, `futuristic`.                                                                            |
| `referenceImageUrl` | string | No       | —                                           | A publicly accessible URL of a reference image to guide the generation. Must be a valid URI.                                                                                                                               |
| `webhook`           | string | No       | —                                           | A URL to receive a POST notification when the job completes. Must be a valid URI.                                                                                                                                          |

## Tips for Effective Prompts

* **Be specific and descriptive.** Include details about the subject, setting, lighting, and composition.
* **Specify the camera angle.** Use terms such as "wide shot", "close-up", or "aerial view" to control framing.
* **Pair with a style.** Combine your prompt with the `style` parameter for more consistent results. For example, use `"photorealistic"` for lifelike images or `"artistic"` for a painterly look.
* **Keep prompts focused.** A single clear subject with a well-defined setting produces better results than a prompt that tries to describe too many elements at once.

## Next Steps

* [Generate Image from Reference Image](/guides/ai-studio/image-from-reference) to use an existing image as a visual guide
* [Generate Image API Reference](/api-reference/ai-studio/generate-image) for the complete parameter documentation
