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

# AI Image Generator API

> Create high-quality images from text descriptions using AI.

export const ToolSection = ({type = "image", outputs = [], title = "", productSlug = "", apiSlug = ""}) => <>
    <CardGroup cols={2}>
      <Card title={`${title} API reference`} icon="webhook" horizontal href={`/api-reference/${type}-projects/${apiSlug}`}>
        Request fields, responses, and examples
      </Card>
      <Card title="API quickstart" icon="forward-fast" horizontal href="/get-started/quick-start">
        Install an SDK and complete your first generation
      </Card>
    </CardGroup>

    <p>
      Check <a href="/billing/overview">API pricing</a> and <a href="/api-reference/models">model credit costs</a>, then <a href={`https://magichour.ai/developer?tab=api-keys&ref=docs-tool-${apiSlug}&utm_source=docs&utm_medium=referral&utm_campaign=tools`}>create an API key</a>.
    </p>
    <p>
      To try {title} without code, use the <a href={`https://magichour.ai/products/${productSlug}${productSlug.includes("?") ? "&" : "?"}utm_source=docs&utm_medium=referral&utm_campaign=tools`}>browser tool</a>.
    </p>

    {outputs && outputs.length > 0 && <Tabs>
        {outputs.map((output, idx) => <Tab key={idx} title={`Example Output ${idx + 1}`}>
            <Frame>
              {type === "video" ? <video controls preload="metadata" playsInline className="rounded-lg h-80" src={`${output.src}#t=0.001`} type={`${output.src?.endsWith("mp4") ? 'video/mp4' : "video/webm"}`}>
                </video> : type === "audio" ? <audio controls preload="metadata" className="w-full" src={output.src}>
                  Your browser does not support the audio element.
                </audio> : <img height="320" className="rounded-lg h-80" src={output.src} alt={`${title} example output ${idx + 1}`} />}
            </Frame>
          </Tab>)}
      </Tabs>}

  </>;

## Overview

AI Image Generator creates high-quality images from text descriptions using advanced AI models. The API generates original artwork, photos, illustrations, and designs based on detailed text prompts with customizable styles, aspect ratios, and resolutions.

**Processing:** See recent [typical API-job times](/api-reference/processing-times). Jobs run
asynchronously, and duration varies with the input, selected settings, and queue load.

<ToolSection
  title="AI Image Generator"
  productSlug="ai-image-generator"
  apiSlug="ai-image-generator"
  type="image"
  outputs={[
{
  src: "/get-started/images/ai-image-generator-example1.jpeg",
},
{
  src: "/get-started/images/ai-image-generator-example2.webp",
},
]}
/>

## How It Works

1. **Write a prompt** - Describe the image you want to create
2. **Choose a style** - Select from 30+ art styles and tools
3. **Set the aspect ratio** - Choose `1:1`, `16:9`, or `9:16`
4. **API generates images** - AI creates images matching your description
5. **Download results** - Retrieve your generated images

## Use Cases

* **Content creation** - Generate images for blogs, social media, marketing
* **Concept art** - Visualize ideas before production
* **Stock photo replacement** - Create custom images on-demand
* **Product mockups** - Generate product visualizations
* **Creative projects** - Artwork, illustrations, and designs

## Best Practices

### Writing Effective Prompts

<Tip>**Be specific and descriptive** - The more detail you provide, the better the results.</Tip>

**✅ Good prompts:**

* "A serene mountain landscape at sunset with vibrant orange and purple colors, dramatic clouds, photorealistic style"
* "Minimalist logo design of a flying bird in blue gradient, vector art style, clean lines"
* "Cozy coffee shop interior with warm lighting, wooden furniture, plants, cinematic photography"

**❌ Avoid:**

* Too vague: "A nice picture"
* Too short: "Mountain"
* Conflicting instructions: "Bright dark image"

### Style Selection

Magic Hour offers 30+ art styles. Match the style to your use case:

| Use Case         | Recommended Styles         |
| :--------------- | :------------------------- |
| Marketing photos | Photorealistic, Cinematic  |
| Illustrations    | Anime, Cartoon, Watercolor |
| Logos & icons    | Vector, Minimalist         |
| Concept art      | Digital Art, Fantasy       |

### Aspect Ratio Guidelines

Set the `aspect_ratio` parameter to control the output shape:

| `aspect_ratio` | Shape     | Best For                                   |
| :------------- | :-------- | :----------------------------------------- |
| `1:1`          | Square    | Profile pictures, thumbnails, social posts |
| `16:9`         | Landscape | Banners, headers, desktop wallpapers       |
| `9:16`         | Portrait  | Stories, mobile wallpapers, posters        |

## Code Examples

### Basic Image Generation

<CodeGroup>
  ```python Python theme={null}
  from magic_hour import Client
  import os

  client = Client(token=os.getenv("MAGIC_HOUR_API_KEY"))

  result = client.v1.ai_image_generator.generate(
      image_count=1,
      aspect_ratio="16:9",
      style={
          "prompt": "A serene mountain landscape at sunset with vibrant colors",
          "tool": "ai-photo-generator"
      },
      name="Mountain Sunset",
      wait_for_completion=True,
      download_outputs=True,
      download_directory="."
  )

  if result.status == "complete":
      print(f"✅ Image complete!")
      print(f"Downloaded to: {result.downloaded_paths}")
      print(f"Credits charged: {result.credits_charged}")
  else:
      print(f"❌ Job failed with status: {result.status}")
      if result.error:
          print(f"Error: {result.error.code}: {result.error.message}")
  ```

  ```javascript Node.js theme={null}
  import { Client } from "magic-hour";

  const client = new Client({ token: process.env.MAGIC_HOUR_API_KEY });

  const result = await client.v1.aiImageGenerator.generate(
    {
      imageCount: 1,
      aspectRatio: "16:9",
      style: {
        prompt: "A serene mountain landscape at sunset with vibrant colors",
        tool: "ai-photo-generator",
      },
      name: "Mountain Sunset",
    },
    {
      waitForCompletion: true,
      downloadOutputs: true,
      downloadDirectory: ".",
    }
  );

  console.log(`Status: ${result.status}`);
  console.log(`Downloaded to: ${result.downloadedPaths}`);
  console.log(`Credits charged: ${result.creditsCharged}`);
  ```
</CodeGroup>

### Square image

<CodeGroup>
  ```python Python theme={null}
  result = client.v1.ai_image_generator.generate(
      image_count=1,
      aspect_ratio="1:1",
      style={
          "prompt": "Cute cat wearing sunglasses, digital art style",
          "tool": "ai-anime-generator"
      },
      name="Cat Illustration",
      wait_for_completion=True,
      download_outputs=True,
      download_directory="."
  )

  if result.status == "complete":
      print(f"✅ Image complete!")
      print(f"Downloaded to: {result.downloaded_paths}")
      print(f"Credits charged: {result.credits_charged}")
  else:
      print(f"❌ Job failed with status: {result.status}")
      if result.error:
          print(f"Error: {result.error.code}: {result.error.message}")
  ```

  ```javascript Node.js theme={null}
  const result = await client.v1.aiImageGenerator.generate(
    {
      imageCount: 1,
      aspectRatio: "1:1",
      style: {
        prompt: "Cute cat wearing sunglasses, digital art style",
        tool: "ai-anime-generator",
      },
      name: "Cat Illustration",
    },
    {
      waitForCompletion: true,
      downloadOutputs: true,
      downloadDirectory: ".",
    }
  );

  console.log(`Status: ${result.status}`);
  console.log(`Downloaded to: ${result.downloadedPaths}`);
  console.log(`Credits charged: ${result.creditsCharged}`);
  ```
</CodeGroup>

### Portrait Orientation

<CodeGroup>
  ```python Python theme={null}
  result = client.v1.ai_image_generator.generate(
      image_count=1,
      aspect_ratio="9:16",
      style={
          "prompt": "Professional business woman in modern office",
          "tool": "ai-photo-generator"
      },
      name="Business Portrait",
      wait_for_completion=True,
      download_outputs=True,
      download_directory="."
  )

  if result.status == "complete":
      print(f"✅ Images complete!")
      print(f"Downloaded to: {result.downloaded_paths}")
      print(f"Credits charged: {result.credits_charged}")
  else:
      print(f"❌ Job failed with status: {result.status}")
      if result.error:
          print(f"Error: {result.error.code}: {result.error.message}")
  ```

  ```javascript Node.js theme={null}
  const result = await client.v1.aiImageGenerator.generate(
    {
      imageCount: 1,
      aspectRatio: "9:16",
      style: {
        prompt: "Professional business woman in modern office",
        tool: "ai-photo-generator",
      },
      name: "Business Portrait",
    },
    {
      waitForCompletion: true,
      downloadOutputs: true,
      downloadDirectory: ".",
    }
  );

  console.log(`Status: ${result.status}`);
  console.log(`Downloaded to: ${result.downloadedPaths}`);
  console.log(`Credits charged: ${result.creditsCharged}`);
  ```
</CodeGroup>

## Pricing

Cost depends on the `model` you choose (the default model is picked automatically and may change over time):

| Model                | Credits per image (from) | Tiers                  |
| :------------------- | :----------------------- | :--------------------- |
| `flux-schnell`       | 5                        | All (including free)   |
| `flux-2-klein`       | 5                        | All (including free)   |
| `z-image-turbo`      | 5                        | All (including free)   |
| `seedream-v4`        | 40                       | Creator, Pro, Business |
| `gpt-image-2`        | 50                       | Creator, Pro, Business |
| `nano-banana`        | 50                       | Creator, Pro, Business |
| `nano-banana-2-lite` | 50                       | Creator, Pro, Business |
| `seedream-v5-pro`    | 75                       | Creator, Pro, Business |
| `nano-banana-2`      | 100                      | Creator, Pro, Business |
| `nano-banana-pro`    | 150                      | Creator, Pro, Business |

Higher resolutions can increase the cost — see the `model` parameter in the [API reference](/api-reference/image-projects/ai-image-generator) for supported resolutions and image counts per model.

<Tip>
  **Try this in our Google Colab Cookbook:** [Run this API with sample
  code](https://colab.research.google.com/drive/1NTHL_lr_s-qBJ-mSecSXPzRLi9_V5JiU?usp=sharing). Just
  add your API key.
</Tip>

## API Reference

<Card title="AI Image Generator API Reference" icon="webhook" href="/api-reference/image-projects/ai-image-generator">
  View full API specification
</Card>

## Related Tools

<CardGroup cols={2}>
  <Card title="AI Image Upscaler" icon="arrow-up" href="/tools/image/image-upscaler">
    Enhance image resolution
  </Card>

  <Card title="Image Background Remover" icon="eraser" href="/tools/image/background-remover">
    Remove image backgrounds
  </Card>
</CardGroup>
