bria-ai
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBria 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
核心功能
| Need | Capability | Use Case |
|---|---|---|
| Create new images | FIBO Generate | Hero images, product shots, illustrations |
| Edit by text | FIBO-Edit | Change colors, modify objects, transform scenes |
| Edit with mask | GenFill/Erase | Precise inpainting, add/replace specific regions |
| Add/Replace/Remove objects | Text-based editing | Add vase, replace apple with pear, remove table |
| Transparent backgrounds | RMBG-2.0 | Extract subjects for overlays, logos, cutouts |
| Background operations | Replace/Blur/Erase | Change, blur, or remove backgrounds |
| Expand images | Outpainting | Extend boundaries, change aspect ratios |
| Upscale images | Super Resolution | Increase resolution 2x or 4x |
| Enhance quality | Enhancement | Improve lighting, colors, details |
| Transform style | Restyle | Oil painting, anime, cartoon, 3D render |
| Change lighting | Relight | Golden hour, spotlight, dramatic lighting |
| Change season | Reseason | Spring, summer, autumn, winter |
| Blend/composite | Image Blending | Apply textures, logos, merge images |
| Text replacement | Rewrite | Change text in images |
| Restore photos | Restoration | Fix old/damaged photos |
| Colorize | Colorization | Add color to B&W, or convert to B&W |
| Sketch to photo | Sketch2Image | Convert drawings to realistic photos |
| Product photography | Lifestyle Shot | Place 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: (square), (hero/banner), (presentation), (mobile/story), (portrait)
1:116:94:39:163:4Advanced: 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:116:94:39:163: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 for full-width banners
16:9 - 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 , then get .
status: "COMPLETED"result.image_urlpython
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_urlpython
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 resultsUsage
使用示例
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 objectprompts = [
"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 resultspython
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 resultsUsage
使用示例
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))
undefinedproducts = ["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))
undefinedParallel 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
常见流水线模式
| Pipeline | Steps | Use Case |
|---|---|---|
| Product → Transparent | generate → remove_background | E-commerce cutouts |
| Product → Lifestyle | generate → remove_background → lifestyle_shot | Marketing photos |
| Edit → Upscale | edit → increase_resolution | High-res edited images |
| Generate → Restyle | generate → restyle | Artistic variations |
| Generate → Variations | generate (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 asynciopython
import asyncioSee "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 for complete endpoint documentation.
references/api-endpoints.md完整接口文档请查看。
references/api-endpoints.mdKey Endpoints
核心接口
Generation
| Endpoint | Purpose |
|---|---|
| Generate images from text (FIBO) |
Edit by Text (No Mask)
| Endpoint | Purpose |
|---|---|
| Edit image with natural language instruction |
| Add objects to image |
| Replace objects in image |
| Remove objects by name |
Edit with Mask
| Endpoint | Purpose |
|---|---|
| Inpaint/generate in masked region |
| Erase masked region |
Background Operations
| Endpoint | Purpose |
|---|---|
| Remove background (RMBG-2.0) |
| Replace with AI-generated background |
| Apply blur to background |
| Remove foreground, fill background |
| Crop tightly around subject |
Image Transformation
| Endpoint | Purpose |
|---|---|
| Outpaint to new aspect ratio |
| Enhance quality and details |
| Upscale 2x or 4x |
| Blend/merge images or textures |
| Change season/weather |
| Transform artistic style |
| Modify lighting |
Text & Restoration
| Endpoint | Purpose |
|---|---|
| Replace text in image |
| Convert sketch to photo |
| Restore old/damaged photos |
| Colorize B&W or convert to B&W |
Product Photography
| Endpoint | Purpose |
|---|---|
| Place product in scene by text |
| Place product on reference background |
Utilities
| Endpoint | Purpose |
|---|---|
| Generate JSON instruction (no image) |
| Check async request status |
生成类
| 接口 | 用途 |
|---|---|
| 通过文本生成图片(FIBO) |
文本式编辑(无需蒙版)
| 接口 | 用途 |
|---|---|
| 使用自然语言指令编辑图片 |
| 为图片添加物体 |
| 替换图片中的物体 |
| 通过名称移除图片中的物体 |
蒙版式编辑
| 接口 | 用途 |
|---|---|
| 在蒙版区域内修复/生成内容 |
| 移除蒙版区域内容 |
背景操作类
| 接口 | 用途 |
|---|---|
| 移除背景(RMBG-2.0) |
| 替换为AI生成的背景 |
| 为背景添加模糊效果 |
| 移除前景并填充背景 |
| 紧贴主体裁剪图片 |
图片转换类
| 接口 | 用途 |
|---|---|
| 扩展图片至新宽高比(Outpainting) |
| 增强图片画质与细节 |
| 将图片放大2倍或4倍 |
| 融合/合并图片或纹理 |
| 更改季节/天气 |
| 转换艺术风格 |
| 调整光线效果 |
文本与修复类
| 接口 | 用途 |
|---|---|
| 替换图片中的文字 |
| 将草图转换为照片 |
| 修复老旧/损坏照片 |
| 为黑白图片上色或转为黑白 |
产品摄影类
| 接口 | 用途 |
|---|---|
| 通过文本将产品置入场景 |
| 将产品置入参考背景中 |
工具类
| 接口 | 用途 |
|---|---|
| 生成JSON格式指令(不生成图片) |
| 检查异步请求状态 |
Authentication
认证方式
All requests need header:
api_tokenapi_token: YOUR_BRIA_API_KEY所有请求均需携带请求头:
api_tokenapi_token: YOUR_BRIA_API_KEYRelated 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输出结果的后期处理