> ## 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.

# Face Swap Photo API

> Replace faces in photos with realistic precision and natural blending.

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

Face Swap Photo lets you replace faces in static images with realistic precision and natural blending. The API swaps faces between two photos while preserving facial expressions, lighting conditions, and image quality for seamless results.

**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="Face Swap Photo"
  productSlug="face-swap?mode=photo"
  apiSlug="face-swap-photo"
  type="image"
  outputs={[
{
  src: "/get-started/images/faceswapphotoexample1.jpg",
},
{
  src: "/get-started/images/mr-bean-swap.jpeg",
},
]}
/>

## How It Works

1. **Provide a source face** - Upload an image containing the face you want to use
2. **Provide a target image** - Upload the image where you want to swap the face
3. **API processes the swap** - AI detects faces, aligns features, and blends seamlessly
4. **Download the result** - Retrieve your face-swapped image

## Use Cases

* **Entertainment content** - Create fun social media content and memes
* **Privacy protection** - Replace faces to anonymize individuals in photos
* **Creative projects** - Character replacement in digital art and design
* **Marketing** - Personalized ad experiences with customer faces
* **Photo editing apps** - Build face swap features into your application

## Best Practices

### Image Quality

<Tip>
  **Use high-resolution images** - Higher quality source images produce better results. Aim for at
  least 512x512 pixels for the face area.
</Tip>

* **Clear, well-lit faces** - Ensure faces are clearly visible with good lighting
* **Front-facing angles work best** - Extreme profile angles may reduce quality
* **Avoid obstructions** - Glasses, hands, or hair covering the face can affect results
* **Similar lighting conditions** - Match lighting between source and target for more natural results

### Face Detection Tips

* **One clear face per image** - The API works best with a single prominent face
* **Visible facial features** - Eyes, nose, and mouth should all be visible
* **Neutral to moderate expressions** - Extreme expressions may affect alignment

### Common Issues and Solutions

| Issue              | Cause                      | Solution                                 |
| :----------------- | :------------------------- | :--------------------------------------- |
| Face not detected  | Face too small or obscured | Use a clearer, larger face image         |
| Unnatural blending | Lighting mismatch          | Match lighting between source and target |
| Distorted features | Extreme angle difference   | Use more similar face angles             |
| Low quality output | Low resolution input       | Use higher resolution images             |

## Multiple faces

`assets.face_swap_mode` defaults to `all-faces`, which uses `source_file_path` to replace every detected target face. For selective swaps, use `individual-faces` and provide up to 5 `face_mappings` with `original_face` and `new_face`. Obtain `original_face` paths from [face detection](/api-reference/files/get-face-detection-details).

## Code Examples

### Basic Face Swap

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

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

  result = client.v1.face_swap_photo.generate(
      assets={
          "source_file_path": "https://raw.githubusercontent.com/runshouse/Sample_Assets/main/tomcruise.png",
          "target_file_path": "https://raw.githubusercontent.com/runshouse/Sample_Assets/main/lebron.jpg"
      },
      name="My Face Swap",
      wait_for_completion=True,
      download_outputs=True,
      download_directory="."
  )

  if result.status == "complete":
      print(f"✅ Face swap 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.faceSwapPhoto.generate(
    {
      assets: {
        sourceFilePath:
          "https://raw.githubusercontent.com/runshouse/Sample_Assets/main/tomcruise.png",
        targetFilePath: "https://raw.githubusercontent.com/runshouse/Sample_Assets/main/lebron.jpg",
      },
      name: "My Face Swap",
    },
    {
      waitForCompletion: true,
      downloadOutputs: true,
      downloadDirectory: ".",
    }
  );

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

## Pricing

Face Swap Photo uses a flat credit cost per image:

| Output            | Credits    |
| :---------------- | :--------- |
| 1 face swap image | 10 credits |

<Info>
  Credits are charged when the job is created. If the job fails, credits are refunded automatically.
</Info>

<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

For complete API details including all parameters and response formats:

<Card title="Face Swap Photo API Reference" icon="webhook" href="/api-reference/image-projects/face-swap-photo">
  View full API specification
</Card>

## Error Handling

Request failures return a `code` and `message`; for example, `invalid_request` indicates invalid parameters and `insufficient_credits` means the account needs more credits. See the [API reference](/api-reference/image-projects/face-swap-photo) for request error responses.

A render failure appears as `status: "error"` in [image project details](/api-reference/image-projects/get-image-details), with `error.code` and `error.message`. For example, `no_source_face` means the API could not detect a face in the source. Inspect the returned message before retrying.

## Related Guides and Tools

<CardGroup cols={2}>
  <Card title="Bulk Face Swap Guide" icon="code" href="/get-started/bulk-face-swap">
    Process a bounded list while preserving project IDs and recovery state
  </Card>

  <Card title="Head Swap" icon="user" href="/tools/image/head-swap">
    Replace the full head while retaining the body and scene
  </Card>

  <Card title="Body Swap" icon="person" href="/tools/image/body-swap">
    Place a person into a different scene
  </Card>

  <Card title="Face Swap Video" icon="video" href="/tools/video/face-swap-video">
    Swap faces in videos with frame-by-frame precision
  </Card>

  <Card title="AI Headshot Generator" icon="user" href="/tools/image/headshot-generator">
    Generate professional headshots from a single photo
  </Card>
</CardGroup>
