bria-ai

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bria Visual Asset Generator

Bria视觉资产生成工具

Generate production-ready visual assets for websites, presentations, documents, and applications using Bria's commercially-safe AI models.
使用Bria的商用安全AI模型,为网站、演示文稿、文档和应用生成可投入生产的视觉资产。

When to Use This Skill

何时使用该工具

  • Website/App Development: Hero images, product photos, backgrounds, illustrations
  • Presentations: Slides visuals, diagrams, icons, cover images
  • Documents: Report graphics, infographics, headers, decorative elements
  • Marketing: Social media assets, banners, promotional images
  • E-commerce: Product photography, lifestyle shots, catalog images
  • Batch Generation: Multiple images with different prompts concurrently
  • Pipeline Workflows: Chained operations (generate → edit → remove background → lifestyle shot)
  • 网站/应用开发:首屏图、产品照片、背景图、插画
  • 演示文稿:幻灯片视觉元素、图表、图标、封面图
  • 文档:报告图表、信息图、页眉、装饰元素
  • 营销推广:社交媒体资产、横幅、宣传图片
  • 电商领域:产品摄影图、场景图、商品目录图片
  • 批量生成:同时生成多个不同提示词的图片
  • 流水线工作流:链式操作(生成→编辑→移除背景→场景合成)

Core Capabilities

核心功能

NeedCapabilityUse Case
Create new imagesFIBO GenerateHero images, product shots, illustrations
Edit by textFIBO-EditChange colors, modify objects, transform scenes
Edit with maskGenFill/ErasePrecise inpainting, add/replace specific regions
Add/Replace/Remove objectsText-based editingAdd vase, replace apple with pear, remove table
Transparent backgroundsRMBG-2.0Extract subjects for overlays, logos, cutouts
Background operationsReplace/Blur/EraseChange, blur, or remove backgrounds
Expand imagesOutpaintingExtend boundaries, change aspect ratios
Upscale imagesSuper ResolutionIncrease resolution 2x or 4x
Enhance qualityEnhancementImprove lighting, colors, details
Transform styleRestyleOil painting, anime, cartoon, 3D render
Change lightingRelightGolden hour, spotlight, dramatic lighting
Change seasonReseasonSpring, summer, autumn, winter
Blend/compositeImage BlendingApply textures, logos, merge images
Text replacementRewriteChange text in images
Restore photosRestorationFix old/damaged photos
ColorizeColorizationAdd color to B&W, or convert to B&W
Sketch to photoSketch2ImageConvert drawings to realistic photos
Product photographyLifestyle ShotPlace products in scenes
需求功能适用场景
创建新图片FIBO Generate首屏图、产品图、插画
文本指令编辑FIBO-Edit更改颜色、修改物体、转换场景
蒙版编辑GenFill/Erase精准修复、添加/替换特定区域
添加/替换/移除物体文本式编辑添加花瓶、将苹果替换为梨、移除桌子
透明背景RMBG-2.0提取主体用于叠加、Logo、抠图
背景操作替换/模糊/移除更改、模糊或移除背景
扩展图片Outpainting扩展边界、更改宽高比
图片放大Super Resolution将分辨率提升2倍或4倍
画质增强Enhancement改善光线、色彩、细节
风格转换Restyle油画、动漫、卡通、3D渲染风格
光线调整Relight黄金时段光、聚光灯、戏剧化光线
季节转换Reseason春、夏、秋、冬场景
图片融合Image Blending应用纹理、Logo、合并图片
文本替换Rewrite更改图片中的文字
照片修复Restoration修复老旧/损坏照片
上色处理Colorization为黑白图片上色或转为黑白
草图转照片Sketch2Image将手绘转为真实照片
产品场景图Lifestyle Shot将产品置入场景中

Quick Reference

快速参考

Generate an Image (FIBO)

生成图片(FIBO)

bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/generate" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "your description",
    "aspect_ratio": "16:9"
  }'
Aspect ratios:
1:1
(square),
16:9
(hero/banner),
4:3
(presentation),
9:16
(mobile/story),
3:4
(portrait)
Advanced: For precise, deterministic control over generation, use VGL structured prompts instead of natural language. VGL defines every visual attribute (objects, lighting, composition) as explicit JSON.
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/generate" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "your description",
    "aspect_ratio": "16:9"
  }'
宽高比
1:1
(正方形)、
16:9
(首屏/横幅)、
4:3
(演示文稿)、
9:16
(移动端/故事页)、
3:4
(竖版)
高级用法:如需对生成过程进行精准、确定性控制,请使用**VGL结构化提示词**替代自然语言。VGL以明确的JSON格式定义所有视觉属性(物体、光线、构图)。

Remove Background (RMBG-2.0)

移除背景(RMBG-2.0)

bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/remove_background" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image": "https://..."}'
Returns PNG with transparency.
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/remove_background" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image": "https://..."}'
返回带透明通道的PNG图片。

Edit Image (FIBO-Edit) - No Mask Required

编辑图片(FIBO-Edit)- 无需蒙版

Edit any image with natural language instructions:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "images": ["https://..."],
    "instruction": "change the mug to red"
  }'
Python example:
python
from bria_client import BriaClient
client = BriaClient()
result = client.edit_image(image_url, "change the mug to red")
print(result['result']['image_url'])
使用自然语言指令编辑任意图片:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "images": ["https://..."],
    "instruction": "change the mug to red"
  }'
Python示例:
python
from bria_client import BriaClient
client = BriaClient()
result = client.edit_image(image_url, "change the mug to red")
print(result['result']['image_url'])

Edit Image Region with Mask (FIBO-Edit)

蒙版编辑图片区域(FIBO-Edit)

For precise control over which region to edit:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/gen_fill" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "https://...",
    "mask": "https://...",
    "prompt": "what to generate in masked area"
  }'
如需精准控制编辑区域:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/gen_fill" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "https://...",
    "mask": "https://...",
    "prompt": "what to generate in masked area"
  }'

Expand Image (Outpainting)

扩展图片(Outpainting)

Extend image boundaries to new aspect ratio:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/expand" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "base64-or-url",
    "aspect_ratio": "16:9",
    "prompt": "coffee shop background, wooden table"
  }'
扩展图片边界至新的宽高比:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/expand" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "base64-or-url",
    "aspect_ratio": "16:9",
    "prompt": "coffee shop background, wooden table"
  }'

Upscale Image

放大图片

Increase image resolution 2x or 4x:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/increase_resolution" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image": "https://...", "scale": 2}'
将图片分辨率提升2倍或4倍:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/increase_resolution" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image": "https://...", "scale": 2}'

Product Lifestyle Shot

产品场景合成图

Place a product in a lifestyle scene:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/lifestyle_shot_by_text" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "https://product-with-transparent-bg.png",
    "prompt": "modern kitchen countertop, natural morning light"
  }'

将产品置入生活场景中:
bash
curl -X POST "https://engine.prod.bria-api.com/v2/image/edit/lifestyle_shot_by_text" \
  -H "api_token: $BRIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image": "https://product-with-transparent-bg.png",
    "prompt": "modern kitchen countertop, natural morning light"
  }'

Asset Generation Workflows

资产生成工作流

Website Hero Images

网站首屏图

Generate wide banner images for landing pages:
json
{
  "prompt": "Modern tech startup workspace with developers collaborating, bright natural lighting, clean minimal aesthetic",
  "aspect_ratio": "16:9",
  "negative_prompt": "cluttered, dark, low quality"
}
Tips for hero images:
  • Use
    16:9
    for full-width banners
  • Describe lighting and mood explicitly
  • Include "professional", "high quality", "commercial" for polished results
  • Specify "clean background" or "minimal" for text overlay space
为着陆页生成宽幅横幅图片:
json
{
  "prompt": "Modern tech startup workspace with developers collaborating, bright natural lighting, clean minimal aesthetic",
  "aspect_ratio": "16:9",
  "negative_prompt": "cluttered, dark, low quality"
}
首屏图技巧:
  • 使用
    16:9
    比例制作全屏横幅
  • 明确描述光线和氛围
  • 添加"professional"、"high quality"、"commercial"等关键词以获得精致效果
  • 指定"clean background"或"minimal"以预留文字叠加空间

Product Photography

产品摄影图

Generate e-commerce style product shots:
json
{
  "prompt": "Professional product photo of [item] on white studio background, soft shadows, commercial photography lighting",
  "aspect_ratio": "1:1"
}
Then remove background for transparent PNG to composite anywhere:
json
{"image": "generated_image_url"}
生成电商风格的产品图:
json
{
  "prompt": "Professional product photo of [item] on white studio background, soft shadows, commercial photography lighting",
  "aspect_ratio": "1:1"
}
随后移除背景以获得透明PNG,便于在任意场景合成:
json
{"image": "generated_image_url"}

Presentation Visuals

演示文稿视觉元素

Generate slides-ready images:
json
{
  "prompt": "Abstract visualization of data analytics, blue and purple gradient, modern corporate style, clean composition with space for text",
  "aspect_ratio": "16:9"
}
Common presentation themes:
  • "Abstract technology background" - tech slides
  • "Business team collaboration" - culture slides
  • "Growth chart visualization" - metrics slides
  • "Minimalist geometric patterns" - section dividers
生成适用于幻灯片的图片:
json
{
  "prompt": "Abstract visualization of data analytics, blue and purple gradient, modern corporate style, clean composition with space for text",
  "aspect_ratio": "16:9"
}
常见演示文稿主题:
  • "Abstract technology background" - 科技类幻灯片
  • "Business team collaboration" - 企业文化类幻灯片
  • "Growth chart visualization" - 数据指标类幻灯片
  • "Minimalist geometric patterns" - 章节分隔符

Document Graphics

文档图表

Generate report or article images:
json
{
  "prompt": "Isometric illustration of cloud computing infrastructure, flat design, vibrant colors, white background",
  "aspect_ratio": "4:3"
}
生成报告或文章用图片:
json
{
  "prompt": "Isometric illustration of cloud computing infrastructure, flat design, vibrant colors, white background",
  "aspect_ratio": "4:3"
}

Icons and Illustrations

图标与插画

For icons, generate then remove background:
json
{
  "prompt": "3D icon of a shield with checkmark, glossy material, soft gradient background, app icon style",
  "aspect_ratio": "1:1"
}
Then use RMBG-2.0 to get transparent PNG.
制作图标时,先生成图片再移除背景:
json
{
  "prompt": "3D icon of a shield with checkmark, glossy material, soft gradient background, app icon style",
  "aspect_ratio": "1:1"
}
随后使用RMBG-2.0工具获取透明PNG图标。

Social Media Assets

社交媒体资产

Instagram post (1:1):
json
{
  "prompt": "Lifestyle photo of coffee and laptop on wooden desk, morning light, cozy atmosphere",
  "aspect_ratio": "1:1"
}
Story/Reel (9:16):
json
{
  "prompt": "Vertical product showcase of smartphone, floating in gradient background, tech aesthetic",
  "aspect_ratio": "9:16"
}

Instagram帖子(1:1):
json
{
  "prompt": "Lifestyle photo of coffee and laptop on wooden desk, morning light, cozy atmosphere",
  "aspect_ratio": "1:1"
}
故事/短视频(9:16):
json
{
  "prompt": "Vertical product showcase of smartphone, floating in gradient background, tech aesthetic",
  "aspect_ratio": "9:16"
}

Prompt Engineering Tips

提示词工程技巧

Be Specific About Style

明确风格描述

  • "professional product photography" vs "casual snapshot"
  • "flat design illustration" vs "3D rendered"
  • "corporate modern" vs "playful colorful"
  • "professional product photography" 对比 "casual snapshot"
  • "flat design illustration" 对比 "3D rendered"
  • "corporate modern" 对比 "playful colorful"

Specify Technical Details

指定技术细节

  • Lighting: "soft natural light", "studio lighting", "dramatic shadows"
  • Background: "white studio", "gradient", "blurred office", "transparent"
  • Composition: "centered", "rule of thirds", "negative space on left for text"
  • 光线:"soft natural light"、"studio lighting"、"dramatic shadows"
  • 背景:"white studio"、"gradient"、"blurred office"、"transparent"
  • 构图:"centered"、"rule of thirds"、"negative space on left for text"

Quality Keywords

画质关键词

Add these for polished results:
  • "high quality", "professional", "commercial grade"
  • "4K", "detailed", "sharp focus"
  • "award-winning photography" (for photos)
添加以下关键词以获得精致效果:
  • "high quality"、"professional"、"commercial grade"
  • "4K"、"detailed"、"sharp focus"
  • "award-winning photography"(针对照片类生成)

Negative Prompts

反向提示词

Exclude unwanted elements:
  • "blurry, low quality, pixelated"
  • "text, watermark, logo"
  • "cluttered, busy, messy"

排除不需要的元素:
  • "blurry, low quality, pixelated"
  • "text, watermark, logo"
  • "cluttered, busy, messy"

Async Response Handling

异步响应处理

All endpoints return async responses:
json
{
  "request_id": "uuid",
  "status_url": "https://engine.prod.bria-api.com/v2/status/uuid"
}
Poll the status_url until
status: "COMPLETED"
, then get
result.image_url
.
python
import requests, time

def get_result(status_url, api_key):
    while True:
        r = requests.get(status_url, headers={"api_token": api_key})
        data = r.json()
        if data["status"] == "COMPLETED":
            return data["result"]["image_url"]
        if data["status"] == "FAILED":
            raise Exception(data.get("error"))
        time.sleep(2)

所有接口均返回异步响应:
json
{
  "request_id": "uuid",
  "status_url": "https://engine.prod.bria-api.com/v2/status/uuid"
}
轮询status_url直至状态变为
status: "COMPLETED"
,即可获取
result.image_url
python
import requests, time

def get_result(status_url, api_key):
    while True:
        r = requests.get(status_url, headers={"api_token": api_key})
        data = r.json()
        if data["status"] == "COMPLETED":
            return data["result"]["image_url"]
        if data["status"] == "FAILED":
            raise Exception(data.get("error"))
        time.sleep(2)

Batch & Parallel Image Generation

批量与并行图片生成

Generating Multiple Images Concurrently

同时生成多张图片

For generating many images efficiently, launch requests in parallel and poll concurrently:
python
import asyncio
import aiohttp

async def generate_image(session, api_key, prompt, aspect_ratio="1:1"):
    """Launch a single generation request."""
    async with session.post(
        "https://engine.prod.bria-api.com/v2/image/generate",
        headers={"api_token": api_key, "Content-Type": "application/json"},
        json={"prompt": prompt, "aspect_ratio": aspect_ratio}
    ) as resp:
        return await resp.json()

async def poll_status(session, api_key, status_url, timeout=120):
    """Poll until complete or failed."""
    for _ in range(timeout // 2):
        async with session.get(status_url, headers={"api_token": api_key}) as resp:
            data = await resp.json()
            if data["status"] == "COMPLETED":
                return data["result"]["image_url"]
            if data["status"] == "FAILED":
                raise Exception(data.get("error", "Generation failed"))
        await asyncio.sleep(2)
    raise TimeoutError(f"Timeout polling {status_url}")

async def generate_batch(api_key, prompts, aspect_ratio="1:1", max_concurrent=5):
    """Generate multiple images with different prompts concurrently."""
    semaphore = asyncio.Semaphore(max_concurrent)  # Rate limiting

    async def generate_one(prompt):
        async with semaphore:
            async with aiohttp.ClientSession() as session:
                # Launch request
                result = await generate_image(session, api_key, prompt, aspect_ratio)
                # Poll for completion
                return await poll_status(session, api_key, result["status_url"])

    # Run all concurrently
    results = await asyncio.gather(*[generate_one(p) for p in prompts], return_exceptions=True)
    return results
如需高效生成大量图片,可并行发起请求并同时轮询结果:
python
import asyncio
import aiohttp

async def generate_image(session, api_key, prompt, aspect_ratio="1:1"):
    """发起单次生成请求。"""
    async with session.post(
        "https://engine.prod.bria-api.com/v2/image/generate",
        headers={"api_token": api_key, "Content-Type": "application/json"},
        json={"prompt": prompt, "aspect_ratio": aspect_ratio}
    ) as resp:
        return await resp.json()

async def poll_status(session, api_key, status_url, timeout=120):
    """轮询直至请求完成或失败。"""
    for _ in range(timeout // 2):
        async with session.get(status_url, headers={"api_token": api_key}) as resp:
            data = await resp.json()
            if data["status"] == "COMPLETED":
                return data["result"]["image_url"]
            if data["status"] == "FAILED":
                raise Exception(data.get("error", "Generation failed"))
        await asyncio.sleep(2)
    raise TimeoutError(f"Timeout polling {status_url}")

async def generate_batch(api_key, prompts, aspect_ratio="1:1", max_concurrent=5):
    """同时生成多个不同提示词的图片。"""
    semaphore = asyncio.Semaphore(max_concurrent)  # 请求限流

    async def generate_one(prompt):
        async with semaphore:
            async with aiohttp.ClientSession() as session:
                # 发起请求
                result = await generate_image(session, api_key, prompt, aspect_ratio)
                # 轮询结果
                return await poll_status(session, api_key, result["status_url"])

    # 并行执行所有请求
    results = await asyncio.gather(*[generate_one(p) for p in prompts], return_exceptions=True)
    return results

Usage

使用示例

prompts = [ "Professional photo of running shoes on white background", "Professional photo of leather handbag on white background", "Professional photo of smartwatch on white background", "Professional photo of sunglasses on white background", ] image_urls = asyncio.run(generate_batch("YOUR_API_KEY", prompts, max_concurrent=3))

**Key points:**
- Use `asyncio.Semaphore` to limit concurrent requests (recommended: 3-5)
- `return_exceptions=True` prevents one failure from canceling all requests
- Each result is either a URL string or an Exception object
prompts = [ "Professional photo of running shoes on white background", "Professional photo of leather handbag on white background", "Professional photo of smartwatch on white background", "Professional photo of sunglasses on white background", ] image_urls = asyncio.run(generate_batch("YOUR_API_KEY", prompts, max_concurrent=3))

**关键点:**
- 使用`asyncio.Semaphore`限制并发请求数量(推荐:3-5个)
- `return_exceptions=True`可避免单个请求失败导致所有请求被取消
- 每个结果要么是URL字符串,要么是Exception对象

TypeScript/Node.js Parallel Generation

TypeScript/Node.js并行生成

typescript
type AspectRatio = "1:1" | "4:3" | "16:9" | "3:4" | "9:16";

interface BriaResponse {
  request_id: string;
  status_url: string;
}

interface BriaStatusResponse {
  status: "IN_PROGRESS" | "COMPLETED" | "FAILED";
  result?: { image_url: string };
  error?: string;
}

interface GenerateBatchResult {
  prompt: string;
  imageUrl: string | null;
  error: string | null;
}

async function generateBatch(
  apiKey: string,
  prompts: string[],
  aspectRatio: AspectRatio = "1:1",
  maxConcurrent = 5
): Promise<GenerateBatchResult[]> {
  const semaphore = { count: 0, max: maxConcurrent };

  async function withLimit<T>(fn: () => Promise<T>): Promise<T> {
    while (semaphore.count >= semaphore.max) {
      await new Promise(r => setTimeout(r, 100));
    }
    semaphore.count++;
    try {
      return await fn();
    } finally {
      semaphore.count--;
    }
  }

  async function generateOne(prompt: string): Promise<string> {
    return withLimit(async () => {
      // Launch request
      const res = await fetch("https://engine.prod.bria-api.com/v2/image/generate", {
        method: "POST",
        headers: { "api_token": apiKey, "Content-Type": "application/json" },
        body: JSON.stringify({ prompt, aspect_ratio: aspectRatio })
      });
      const { status_url } = (await res.json()) as BriaResponse;

      // Poll for result
      for (let i = 0; i < 60; i++) {
        const statusRes = await fetch(status_url, { headers: { "api_token": apiKey } });
        const data = (await statusRes.json()) as BriaStatusResponse;
        if (data.status === "COMPLETED") return data.result!.image_url;
        if (data.status === "FAILED") throw new Error(data.error || "Generation failed");
        await new Promise(r => setTimeout(r, 2000));
      }
      throw new Error("Timeout waiting for generation");
    });
  }

  const results = await Promise.allSettled(prompts.map(generateOne));

  return results.map((result, i) => ({
    prompt: prompts[i],
    imageUrl: result.status === "fulfilled" ? result.value : null,
    error: result.status === "rejected" ? result.reason.message : null
  }));
}

// Usage
const results = await generateBatch(process.env.BRIA_API_KEY!, [
  "Modern office workspace with natural lighting",
  "Abstract tech background with blue gradient",
  "Professional headshot studio setup"
], "16:9", 3);

results.forEach(r => {
  if (r.imageUrl) console.log(`${r.prompt}: ${r.imageUrl}`);
  else console.log(`${r.prompt}: ${r.error}`);
});

---
typescript
type AspectRatio = "1:1" | "4:3" | "16:9" | "3:4" | "9:16";

interface BriaResponse {
  request_id: string;
  status_url: string;
}

interface BriaStatusResponse {
  status: "IN_PROGRESS" | "COMPLETED" | "FAILED";
  result?: { image_url: string };
  error?: string;
}

interface GenerateBatchResult {
  prompt: string;
  imageUrl: string | null;
  error: string | null;
}

async function generateBatch(
  apiKey: string,
  prompts: string[],
  aspectRatio: AspectRatio = "1:1",
  maxConcurrent = 5
): Promise<GenerateBatchResult[]> {
  const semaphore = { count: 0, max: maxConcurrent };

  async function withLimit<T>(fn: () => Promise<T>): Promise<T> {
    while (semaphore.count >= semaphore.max) {
      await new Promise(r => setTimeout(r, 100));
    }
    semaphore.count++;
    try {
      return await fn();
    } finally {
      semaphore.count--;
    }
  }

  async function generateOne(prompt: string): Promise<string> {
    return withLimit(async () => {
      // 发起请求
      const res = await fetch("https://engine.prod.bria-api.com/v2/image/generate", {
        method: "POST",
        headers: { "api_token": apiKey, "Content-Type": "application/json" },
        body: JSON.stringify({ prompt, aspect_ratio: aspectRatio })
      });
      const { status_url } = (await res.json()) as BriaResponse;

      // 轮询结果
      for (let i = 0; i < 60; i++) {
        const statusRes = await fetch(status_url, { headers: { "api_token": apiKey } });
        const data = (await statusRes.json()) as BriaStatusResponse;
        if (data.status === "COMPLETED") return data.result!.image_url;
        if (data.status === "FAILED") throw new Error(data.error || "Generation failed");
        await new Promise(r => setTimeout(r, 2000));
      }
      throw new Error("Timeout waiting for generation");
    });
  }

  const results = await Promise.allSettled(prompts.map(generateOne));

  return results.map((result, i) => ({
    prompt: prompts[i],
    imageUrl: result.status === "fulfilled" ? result.value : null,
    error: result.status === "rejected" ? result.reason.message : null
  }));
}

// 使用示例
const results = await generateBatch(process.env.BRIA_API_KEY!, [
  "Modern office workspace with natural lighting",
  "Abstract tech background with blue gradient",
  "Professional headshot studio setup"
], "16:9", 3);

results.forEach(r => {
  if (r.imageUrl) console.log(`${r.prompt}: ${r.imageUrl}`);
  else console.log(`${r.prompt}: ${r.error}`);
});

Pipeline Workflows

流水线工作流

Chain multiple operations on images (generate → edit → remove background).
对图片执行多步链式操作(生成→编辑→移除背景)。

Complete Pipeline Example

完整流水线示例

python
async def product_pipeline(api_key, product_descriptions, scene_prompt):
    """
    Pipeline: Generate product → Remove background → Place in lifestyle scene
    """
    async with aiohttp.ClientSession() as session:
        results = []

        for desc in product_descriptions:
            # Step 1: Generate product image
            gen_result = await generate_image(session, api_key,
                f"Professional product photo of {desc} on white background, studio lighting",
                aspect_ratio="1:1")
            product_url = await poll_status(session, api_key, gen_result["status_url"])

            # Step 2: Remove background
            async with session.post(
                "https://engine.prod.bria-api.com/v2/image/edit/remove_background",
                headers={"api_token": api_key, "Content-Type": "application/json"},
                json={"image": product_url}
            ) as resp:
                rmbg_result = await resp.json()
            transparent_url = await poll_status(session, api_key, rmbg_result["status_url"])

            # Step 3: Place in lifestyle scene
            async with session.post(
                "https://engine.prod.bria-api.com/v2/image/edit/lifestyle_shot_by_text",
                headers={"api_token": api_key, "Content-Type": "application/json"},
                json={"image": transparent_url, "prompt": scene_prompt}
            ) as resp:
                lifestyle_result = await resp.json()
            final_url = await poll_status(session, api_key, lifestyle_result["status_url"])

            results.append({
                "product": desc,
                "original": product_url,
                "transparent": transparent_url,
                "lifestyle": final_url
            })

        return results
python
async def product_pipeline(api_key, product_descriptions, scene_prompt):
    """
    流水线:生成产品图 → 移除背景 → 置入生活场景
    """
    async with aiohttp.ClientSession() as session:
        results = []

        for desc in product_descriptions:
            # 步骤1:生成产品图
            gen_result = await generate_image(session, api_key,
                f"Professional product photo of {desc} on white background, studio lighting",
                aspect_ratio="1:1")
            product_url = await poll_status(session, api_key, gen_result["status_url"])

            # 步骤2:移除背景
            async with session.post(
                "https://engine.prod.bria-api.com/v2/image/edit/remove_background",
                headers={"api_token": api_key, "Content-Type": "application/json"},
                json={"image": product_url}
            ) as resp:
                rmbg_result = await resp.json()
            transparent_url = await poll_status(session, api_key, rmbg_result["status_url"])

            # 步骤3:置入生活场景
            async with session.post(
                "https://engine.prod.bria-api.com/v2/image/edit/lifestyle_shot_by_text",
                headers={"api_token": api_key, "Content-Type": "application/json"},
                json={"image": transparent_url, "prompt": scene_prompt}
            ) as resp:
                lifestyle_result = await resp.json()
            final_url = await poll_status(session, api_key, lifestyle_result["status_url"])

            results.append({
                "product": desc,
                "original": product_url,
                "transparent": transparent_url,
                "lifestyle": final_url
            })

        return results

Usage

使用示例

products = ["coffee mug", "water bottle", "notebook"] scene = "modern minimalist desk, natural morning light, plants in background" results = asyncio.run(product_pipeline("YOUR_API_KEY", products, scene))
undefined
products = ["coffee mug", "water bottle", "notebook"] scene = "modern minimalist desk, natural morning light, plants in background" results = asyncio.run(product_pipeline("YOUR_API_KEY", products, scene))
undefined

Parallel Pipeline (Advanced)

并行流水线(高级用法)

Process multiple products through the pipeline concurrently:
python
async def parallel_pipeline(api_key, products, scene_prompt, max_concurrent=3):
    """Run full pipeline for multiple products in parallel."""
    semaphore = asyncio.Semaphore(max_concurrent)

    async def process_one(product):
        async with semaphore:
            return await single_product_pipeline(api_key, product, scene_prompt)

    return await asyncio.gather(*[process_one(p) for p in products], return_exceptions=True)
同时对多个产品执行完整流水线操作:
python
async def parallel_pipeline(api_key, products, scene_prompt, max_concurrent=3):
    """并行对多个产品执行完整流水线操作。"""
    semaphore = asyncio.Semaphore(max_concurrent)

    async def process_one(product):
        async with semaphore:
            return await single_product_pipeline(api_key, product, scene_prompt)

    return await asyncio.gather(*[process_one(p) for p in products], return_exceptions=True)

Common Pipeline Patterns

常见流水线模式

PipelineStepsUse Case
Product → Transparentgenerate → remove_backgroundE-commerce cutouts
Product → Lifestylegenerate → remove_background → lifestyle_shotMarketing photos
Edit → Upscaleedit → increase_resolutionHigh-res edited images
Generate → Restylegenerate → restyleArtistic variations
Generate → Variationsgenerate (num_results=4)A/B testing options

流水线步骤适用场景
产品图 → 透明背景生成 → remove_background电商抠图
产品图 → 场景图生成 → remove_background → lifestyle_shot营销照片
编辑 → 放大编辑 → increase_resolution高分辨率编辑图
生成 → 风格转换生成 → restyle艺术化变体
生成 → 多版本生成(num_results=4)A/B测试备选方案

Integration Examples

集成示例

React/Next.js Component

React/Next.js组件

jsx
// Generate and display a hero image
const [imageUrl, setImageUrl] = useState(null);

async function generateHero(prompt) {
  const res = await fetch('/api/bria/generate', {
    method: 'POST',
    body: JSON.stringify({ prompt, aspect_ratio: '16:9' })
  });
  const { image_url } = await res.json();
  setImageUrl(image_url);
}
jsx
// 生成并展示首屏图
const [imageUrl, setImageUrl] = useState(null);

async function generateHero(prompt) {
  const res = await fetch('/api/bria/generate', {
    method: 'POST',
    body: JSON.stringify({ prompt, aspect_ratio: '16:9' })
  });
  const { image_url } = await res.json();
  setImageUrl(image_url);
}

Python Script for Batch Generation

Python批量生成脚本

python
import asyncio
python
import asyncio

See "Batch & Parallel Image Generation" section for generate_batch function

请查看「批量与并行图片生成」章节中的generate_batch函数

async def main(): api_key = "YOUR_API_KEY" products = ["running shoes", "leather bag", "smart watch"] prompts = [f"Professional product photo of {p} on white background" for p in products]
results = await generate_batch(api_key, prompts, aspect_ratio="1:1", max_concurrent=3)

for product, result in zip(products, results):
    if isinstance(result, Exception):
        print(f"{product}: FAILED - {result}")
    else:
        print(f"{product}: {result}")
asyncio.run(main())

---
async def main(): api_key = "YOUR_API_KEY" products = ["running shoes", "leather bag", "smart watch"] prompts = [f"Professional product photo of {p} on white background" for p in products]
results = await generate_batch(api_key, prompts, aspect_ratio="1:1", max_concurrent=3)

for product, result in zip(products, results):
    if isinstance(result, Exception):
        print(f"{product}: FAILED - {result}")
    else:
        print(f"{product}: {result}")
asyncio.run(main())

---

API Reference

API参考

See
references/api-endpoints.md
for complete endpoint documentation.
完整接口文档请查看
references/api-endpoints.md

Key Endpoints

核心接口

Generation
EndpointPurpose
POST /v2/image/generate
Generate images from text (FIBO)
Edit by Text (No Mask)
EndpointPurpose
POST /v2/image/edit
Edit image with natural language instruction
POST /v2/image/edit/add_object_by_text
Add objects to image
POST /v2/image/edit/replace_object_by_text
Replace objects in image
POST /v2/image/edit/erase_by_text
Remove objects by name
Edit with Mask
EndpointPurpose
POST /v2/image/edit/gen_fill
Inpaint/generate in masked region
POST /v2/image/edit/erase
Erase masked region
Background Operations
EndpointPurpose
POST /v2/image/edit/remove_background
Remove background (RMBG-2.0)
POST /v2/image/edit/replace_background
Replace with AI-generated background
POST /v2/image/edit/blur_background
Apply blur to background
POST /v2/image/edit/erase_foreground
Remove foreground, fill background
POST /v2/image/edit/crop_foreground
Crop tightly around subject
Image Transformation
EndpointPurpose
POST /v2/image/edit/expand
Outpaint to new aspect ratio
POST /v2/image/edit/enhance
Enhance quality and details
POST /v2/image/edit/increase_resolution
Upscale 2x or 4x
POST /v2/image/edit/blend
Blend/merge images or textures
POST /v2/image/edit/reseason
Change season/weather
POST /v2/image/edit/restyle
Transform artistic style
POST /v2/image/edit/relight
Modify lighting
Text & Restoration
EndpointPurpose
POST /v2/image/edit/replace_text
Replace text in image
POST /v2/image/edit/sketch_to_image
Convert sketch to photo
POST /v2/image/edit/restore
Restore old/damaged photos
POST /v2/image/edit/colorize
Colorize B&W or convert to B&W
Product Photography
EndpointPurpose
POST /v2/image/edit/lifestyle_shot_by_text
Place product in scene by text
POST /v2/image/edit/shot_by_image
Place product on reference background
Utilities
EndpointPurpose
POST /v2/structured_instruction/generate
Generate JSON instruction (no image)
GET /v2/status/{id}
Check async request status
生成类
接口用途
POST /v2/image/generate
通过文本生成图片(FIBO)
文本式编辑(无需蒙版)
接口用途
POST /v2/image/edit
使用自然语言指令编辑图片
POST /v2/image/edit/add_object_by_text
为图片添加物体
POST /v2/image/edit/replace_object_by_text
替换图片中的物体
POST /v2/image/edit/erase_by_text
通过名称移除图片中的物体
蒙版式编辑
接口用途
POST /v2/image/edit/gen_fill
在蒙版区域内修复/生成内容
POST /v2/image/edit/erase
移除蒙版区域内容
背景操作类
接口用途
POST /v2/image/edit/remove_background
移除背景(RMBG-2.0)
POST /v2/image/edit/replace_background
替换为AI生成的背景
POST /v2/image/edit/blur_background
为背景添加模糊效果
POST /v2/image/edit/erase_foreground
移除前景并填充背景
POST /v2/image/edit/crop_foreground
紧贴主体裁剪图片
图片转换类
接口用途
POST /v2/image/edit/expand
扩展图片至新宽高比(Outpainting)
POST /v2/image/edit/enhance
增强图片画质与细节
POST /v2/image/edit/increase_resolution
将图片放大2倍或4倍
POST /v2/image/edit/blend
融合/合并图片或纹理
POST /v2/image/edit/reseason
更改季节/天气
POST /v2/image/edit/restyle
转换艺术风格
POST /v2/image/edit/relight
调整光线效果
文本与修复类
接口用途
POST /v2/image/edit/replace_text
替换图片中的文字
POST /v2/image/edit/sketch_to_image
将草图转换为照片
POST /v2/image/edit/restore
修复老旧/损坏照片
POST /v2/image/edit/colorize
为黑白图片上色或转为黑白
产品摄影类
接口用途
POST /v2/image/edit/lifestyle_shot_by_text
通过文本将产品置入场景
POST /v2/image/edit/shot_by_image
将产品置入参考背景中
工具类
接口用途
POST /v2/structured_instruction/generate
生成JSON格式指令(不生成图片)
GET /v2/status/{id}
检查异步请求状态

Authentication

认证方式

All requests need
api_token
header:
api_token: YOUR_BRIA_API_KEY

所有请求均需携带
api_token
请求头:
api_token: YOUR_BRIA_API_KEY

Related Skills

相关工具

  • vgl - Write structured VGL (Visual Generation Language) JSON prompts for precise, deterministic control over FIBO image generation. Use VGL for reproducible outputs with explicit visual attributes.
  • image-utils - Classic image manipulation (resize, crop, composite, watermarks) for post-processing Bria outputs
  • vgl - 编写结构化VGL(视觉生成语言)JSON提示词,对FIBO图片生成进行精准、确定性控制。使用VGL可生成具有明确视觉属性的可复现输出。
  • image-utils - 经典图片处理功能(调整大小、裁剪、合成、水印),用于Bria输出结果的后期处理