> For the complete documentation index, see [llms.txt](https://docs.qolaba.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.qolaba.ai/api-platform/image-generation/replace-background.md).

# Replace Background

Replace or swap the background of any image while preserving the foreground subject using the Image Generation API.

***

### Overview

The Replace Background feature takes an existing photo and rewrites the background based on your text prompt, while keeping the foreground subject intact.

## Replace Background API

`POST /api/v1/images/generate`

**Headers**

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <token>`   |

**How it works:**

```
  Input photo + prompt
        │
        ▼
  [Gemini model understands
   subject vs. background]
        │
        ▼
  New background rendered
  around the subject
        │
        ▼
  Output image returned
```

**Two approaches:**

| Approach                      | When to Use                                   | Models                                               |
| ----------------------------- | --------------------------------------------- | ---------------------------------------------------- |
| **Direct replacement**        | Background is clearly distinct from subject   | `vertex/nano-banana-flash`, `vertex/nano-banana-pro` |
| **Cutout + replace pipeline** | Hair, fur, complex edges, transparent objects | BiRefNet → Nano Banana                               |

***

### Supported Models

Only Gemini-based models support image-to-image editing. Imagen 4 variants are **text-to-image only** and do not accept source images.

| Model                      | Speed    | Max Resolution | Max Source Images | Best For                                        |
| -------------------------- | -------- | -------------- | ----------------- | ----------------------------------------------- |
| `vertex/nano-banana-flash` | Fast     | 4K             | 14                | Rapid iteration, prototyping, batch jobs        |
| `vertex/nano-banana-pro`   | Standard | 4K             | 14                | Production, text in images, precise consistency |

***

### Quick Start

```bash
curl -X POST https://api.platform.qolaba.ai/api/v1/images/generate \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "vertex/nano-banana-flash",
    "prompt": "Replace the background with a modern city skyline at golden hour, keep the subject exactly as-is",
    "image_urls": ["https://cdn.qolaba.ai/1778648245451_d2c9wj0yf2a.jpeg"],
    "quality": "1K",
    "aspect_ratio": "16:9"
  }'
```

**Response `200 OK`:**

```json
{
  "task_id": "task_1705312200000_abc123",
  "images": [
    {
      "url": "https://storage.example.com/result.png",
      "width": 2048,
      "height": 1152,
      "content_type": "image/png"
    }
  ],
  "usage": {
    "images_generated": 1,
    "cost_usd": 0.08,
    "cost_credits": 16
  }
}
```

***

### Request Reference

#### Required Fields

| Field        | Type                | Description                                            |
| ------------ | ------------------- | ------------------------------------------------------ |
| `model`      | `string`            | `vertex/nano-banana-flash` or `vertex/nano-banana-pro` |
| `prompt`     | `string` (max 4000) | Describe the new background. See Prompt Writing Guide. |
| `image_urls` | `string[]`          | Array containing the URL of the source image to edit.  |

#### Optional Fields

| Field                  | Type       | Default | Description                                                                 |
| ---------------------- | ---------- | ------- | --------------------------------------------------------------------------- |
| `quality`              | `string`   | `2K`    | Output resolution. Flash: `512 \| 1K \| 2K \| 4K`. Pro: `1K \| 2K \| 4K`.   |
| `aspect_ratio`         | `string`   | `1:1`   | Output dimensions. See valid values below.                                  |
| `num_images`           | `integer`  | `1`     | Number of variations to generate (1–4).                                     |
| `temperature`          | `number`   | `1.0`   | Creativity level. `0.7–0.9` = faithful, `1.2–1.5` = more creative.          |
| `reference_images`     | `object[]` | —       | Up to 14 reference images for style/environment matching.                   |
| `use_search_grounding` | `boolean`  | `false` | Enable real-time search for factually accurate backgrounds. **Flash only.** |
| `celery`               | `boolean`  | `false` | `true` = async processing, returns `task_id` immediately.                   |
| `call_webhook`         | `boolean`  | `false` | Send a POST callback when generation completes.                             |
| `webhook_url`          | `string`   | —       | Webhook destination URL. Required when `call_webhook: true`.                |
| `webhook_secret`       | `string`   | —       | Secret sent as `x-webhook-secret` header in the callback.                   |

#### Valid `aspect_ratio` Values

```
1:1   3:2   2:3   4:3   3:4   16:9   9:16   4:5   5:4   21:9
```

***

### Payloads by Use Case

#### 1. Simple Background Swap

Replace a busy background with a clean, minimal one.

```json
{
  "model": "vertex/nano-banana-flash",
  "prompt": "Replace the background with a plain white studio backdrop with soft even lighting, keep the subject unchanged",
  "image_urls": ["https://your-cdn.com/product-photo.jpg"],
  "quality": "2K",
  "aspect_ratio": "1:1"
}
```

***

#### 2. Outdoor / Scenic Background

Place the subject in a natural or architectural environment.

```json
{
  "model": "vertex/nano-banana-pro",
  "prompt": "Replace the background with a lush green forest at sunrise with soft fog, preserve the person in the foreground exactly",
  "image_urls": ["https://your-cdn.com/portrait.jpg"],
  "quality": "4K",
  "aspect_ratio": "9:16",
  "temperature": 0.9
}
```

***

#### 3. Product Photography Background

Ideal for e-commerce — clean, professional backgrounds.

```json
{
  "model": "vertex/nano-banana-pro",
  "prompt": "Replace the background with a light grey gradient studio background with subtle shadow underneath the product, keep the product exactly as-is",
  "image_urls": ["https://your-cdn.com/product.jpg"],
  "quality": "2K",
  "aspect_ratio": "1:1",
  "temperature": 0.7,
  "num_images": 3
}
```

***

#### 4. Background Matching a Reference Image

Use a reference photo to match a specific environment or style.

```json
{
  "model": "vertex/nano-banana-pro",
  "prompt": "Swap the background to closely match the environment in the reference image, preserve the foreground subject without any changes",
  "image_urls": ["https://your-cdn.com/subject.jpg"],
  "reference_images": [
    {
      "url": "https://your-cdn.com/target-environment.jpg",
      "description": "Use this as the target background scene and lighting"
    }
  ],
  "quality": "2K",
  "aspect_ratio": "16:9",
  "temperature": 0.85
}
```

***

#### 5. Virtual Meeting / Office Background

Professional background replacement for profile photos or video thumbnails.

```json
{
  "model": "vertex/nano-banana-flash",
  "prompt": "Replace the background with a modern open-plan office with blurred depth-of-field effect, keep the person in the foreground sharp and unchanged",
  "image_urls": ["https://your-cdn.com/headshot.jpg"],
  "quality": "2K",
  "aspect_ratio": "16:9",
  "temperature": 1.0
}
```

***

#### 6. Real-World Context with Search Grounding

Generate a geographically or factually accurate background using live search data. **Nano Banana Flash only.**

```json
{
  "model": "vertex/nano-banana-flash",
  "prompt": "Replace the background with the interior of the Louvre Museum in Paris near the Mona Lisa, keep the subject as-is",
  "image_urls": ["https://your-cdn.com/tourist.jpg"],
  "quality": "2K",
  "aspect_ratio": "4:3",
  "use_search_grounding": true
}
```

***

#### 7. Multiple Variations in One Request

Generate several background options in a single call.

```json
{
  "model": "vertex/nano-banana-flash",
  "prompt": "Replace the background with a vibrant night city street with neon lights and rain reflections, keep the subject exactly as-is",
  "image_urls": ["https://your-cdn.com/portrait.jpg"],
  "quality": "2K",
  "aspect_ratio": "9:16",
  "num_images": 4,
  "temperature": 1.2
}
```

***

### Prompt Writing Guide

The prompt is the most important factor in getting clean background replacement. Follow these principles:

#### Always Anchor the Subject

Include an explicit instruction to preserve the foreground. Without it the model may alter both subject and background.

```
# Good
"Replace the background with a tropical beach at sunset, keep the person in the foreground exactly as-is"

# Risky — may alter the subject too
"A person standing on a tropical beach at sunset"
```

#### Describe the New Background Specifically

Vague prompts lead to inconsistent results. Be specific about lighting, distance, depth of field, and mood.

```
# Vague
"outdoor background"

# Specific
"outdoor park background with soft bokeh blur, overcast natural lighting, green trees in the distance"
```

#### Specify Lighting to Match the Subject

If the source photo has directional light, describe matching light in the background to avoid a compositing-look.

```
"Replace background with a sunset beach, warm golden hour lighting from the right side to match the subject's lighting"
```

#### Use Negative Instructions When Needed

State what you do NOT want to help the model avoid common pitfalls.

```
"Replace the background with a snowy mountain scene. Do not change the subject's clothing, face, or body. No watermarks. No text overlay."
```
