> ## 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 Reference Image

> Create AI-generated images guided by a reference image using the Pictory AI Studio API

This guide shows you how to generate an AI image using both a text prompt and a reference image. The reference image provides visual context that guides the AI model, allowing you to create variations, apply transformations, or produce new compositions inspired by the original.

## What You Will Build

> [card] Reference-Guided Generation
>
> Use an existing image to guide the AI output

> [card] Creative Variations
>
> Generate new images that draw from a source composition

> [card] Subject Replacement
>
> Replace or modify subjects while preserving scene context

> [card] Style Transfer
>
> Apply different visual styles to referenced content

## Before You Begin

Make sure you have:

* A [Pictory API key](https://app.pictory.ai/api-access)
* Node.js or Python installed on your machine
* The required packages installed
* A publicly accessible URL for your reference image

```bash npm theme={null}
npm install axios
```

```bash pip theme={null}
pip install requests
```

## Step-by-Step Guide

### Step 1: Set Up Your Request

Prepare your API credentials, the reference image URL, and the prompt that describes the desired transformation or output.

```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 with reference images
const imageRequest = {
  prompt: "Place the white cat from the second image on the park bench in the first image, keeping the lighting and background unchanged",
  model: "nanobanana2",
  aspectRatio: "16:9",
  style: "photorealistic",
  referenceImageUrls: [
    "https://example.com/images/park-bench-scene.png",
    "https://example.com/images/white-cat.png"
  ]
};
```

```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 with reference images
image_request = {
    "prompt": "Place the white cat from the second image on the park bench in the first image, keeping the lighting and background unchanged",
    "model": "nanobanana2",
    "aspectRatio": "16:9",
    "style": "photorealistic",
    "referenceImageUrls": [
        "https://example.com/images/park-bench-scene.png",
        "https://example.com/images/white-cat.png"
    ]
}
```

> [!NOTE]
>
> Each URL in `referenceImageUrls` must point to a publicly accessible image. Ensure the URLs do not require authentication or session cookies to access. You can send up to 4 references on `seedream3.0`, `nanobanana-lite2`, `nanobanana2`, `nanobanana`, and `nanobanana-pro`; `flux-schnell` does not accept references. The single-value `referenceImageUrl` field from earlier integrations still works and behaves like a one-element list.

### Step 2: Submit the Image Generation Request

Send the request to the AI Studio image generation endpoint. The process is identical to text-to-image generation, with the addition of the `referenceImageUrls` field.

```javascript Node.js theme={null}
async function generateImageFromReference() {
  try {
    console.log("Submitting reference-based 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_from_reference():
    try:
        print("Submitting reference-based 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
```

### Step 3: Poll for the Result

Check the job status at regular intervals until the image is ready.

```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
generateImageFromReference()
  .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_from_reference()
    result = wait_for_image(job_id)
    print("\nDone!")
```

## Understanding the Parameters

| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `prompt` | string | Yes | - | A text description that explains what to generate, referencing or modifying the source image. Must be between 5 and 5,000 characters. |
| `model` | string | No | `seedream3.0` | The AI model to use for generation. Supported values with reference support: `seedream3.0`, `nanobanana-lite2`, `nanobanana2`, `nanobanana`, `nanobanana-pro`. See [Generate Image API](https://docs.pictory.ai/api-reference/ai-studio/generate-image.md) 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`). Honored on edits by `seedream3.0`, `nanobanana-lite2`, `nanobanana2`, and `nanobanana-pro`; `nanobanana` keeps the reference image's ratio. |
| `style` | string | No | - | Visual style to apply to the generated image. Supported values: `photorealistic`, `artistic`, `cartoon`, `minimalist`, `vintage`, `futuristic`. |
| `referenceImageUrls` | array | No | - | 1 to 4 publicly accessible image URLs to edit or combine. Each must be a valid URI. Cannot be sent together with `referenceImageUrl`. |
| `referenceImageUrl` | string | No | - | A single reference image URL, kept for existing integrations. Behaves like a one-element `referenceImageUrls`. |
| `trainingPreset` | string | No | - | `sales-training`, `product-training`, or `soft-skills-training`. Steers prompt enhancement and always turns it on, even when `enhancePrompt` is `false`. |
| `enhancePrompt` | boolean | No | `false` | Set to `true` to rewrite the prompt with the AI enhancer before generation. Off by default: the prompt is sent verbatim. |
| `webhook` | string | No | - | A URL to receive a POST notification when the job completes. Must be a valid URI. |

## Tips for Reference-Based Generation

* **Describe the change clearly.** State what should be modified from the reference image. For example, "Replace the car with a bicycle" is more effective than "Change the vehicle."
* **Mention the reference explicitly.** Use phrases such as "in the referenced image" or "based on the provided image" so the model understands the relationship between the prompt and the reference.
* **Preserve scene context.** If you want to keep the background or composition, say so in the prompt. For example, "Keep the background and lighting unchanged."
* **Say which image is which.** With several references, describe each by position ("the cat from the second image") so the model applies the right one.
* **Combine with styles.** Applying a `style` such as `"artistic"` or `"cartoon"` transforms the reference into a different visual treatment while preserving the subject and layout.

## Next Steps

* [Generate Image from Text Prompt](https://docs.pictory.ai/guides/ai-studio/text-to-image.md) to create images without a reference
* [Generate Image API Reference](https://docs.pictory.ai/api-reference/ai-studio/generate-image.md) for the complete parameter documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.