# Images

## `castle.image.load(name)`

Loads an image by filename (without extension) and returns an integer handle. Place image files (`.png`, `.jpg`, `.jpeg`) in the `images/` directory. Call once (e.g. in `onCreate` or at module top-level) and store the handle for use in `onDraw`.

Returns `nil` if the image is not found. Calling with the same name multiple times returns the same handle — loading is idempotent.

```lua
local playerImg
local bgImg

function onCreate()
  playerImg = castle.image.load("player")      -- loads images/player.png (or .jpg)
  bgImg     = castle.image.load("background")
end

function onDraw()
  if bgImg then
    castle.draw.image(bgImg, -5, -7)
  end
  if playerImg then
    -- Scale a 64×64 image to 1×1 world units, centered at (x, y)
    castle.draw.image(playerImg, x, y, 0, 1/64, 1/64, 32, 32)
  end
end
```

---

## AI image generation

Use `castle-script imagine` to generate images with AI and save them directly into your project's `images/` directory. If `castle-script serve` is running, the image appears in your game immediately via hot-reload.

```bash
# First-time setup: save your API key (Replicate recommended)
castle-script imagine "" --service replicate --set-key <your-key>

# Generate an image (saved as images/dragon.png)
castle-script imagine "a fire-breathing dragon" --name dragon

# Apply a style preset for consistent card art
castle-script imagine "a magic sword" --name sword --style fantasy

# Quick draft for iteration ($0.003, ~0.4s)
castle-script imagine "an elf archer" --name elf --draft
```

All generated images are flat 2D sprites with transparent backgrounds, ready to use as game assets.

| Flag | Description |
|------|-------------|
| `--name <name>` | Output filename stem — saved as `images/<name>.png` (default: `image`) |
| `--service <s>` | AI service: `replicate` (default) or `openai` |
| `--draft` | Faster/cheaper model — Flux Schnell (~$0.003) instead of Flux 1.1 Pro |
| `--style <preset>` | Style preset: `fantasy`, `pixel`, `watercolor`, `noir`, `anime` |
| `--set-key <key>` | Save API key for the selected service and exit |
