|

3步完成 FLUX.2 Pro 和 Max API 接入:BFL 最強圖像生成模型實戰指南

Black Forest Labs 的 FLUX.2 系列已成爲 2025 年最受關注的圖像生成模型之一。如何快速接入 FLUX.2 ProFLUX.2 Max API 是許多開發者和創意工作者關心的問題。本文將提供完整的接入指南,幫助你在 5 分鐘內完成集成。

核心價值: 讀完本文,你將掌握 FLUX.2 Pro/Max API 的調用方法、參數配置技巧,並瞭解如何選擇適合你場景的模型版本。

flux-2-pro-max-api-integration-guide-zh-hant 图示


FLUX.2 系列核心信息速覽

在開始接入之前,先了解 FLUX.2 系列的核心信息:

信息項 詳情
開發公司 Black Forest Labs (德國弗萊堡)
發佈日期 2025年11月25日
核心架構 Latent Flow Matching + Rectified Flow Transformer
視覺語言模型 Mistral-3 24B 參數
最大分辨率 4MP (如 2048×2048)
多圖參考 最多支持 10 張參考圖像
文本輸入 最高 32K tokens

FLUX.2 模型矩陣

模型版本 定位 核心特點 API定價
FLUX.2 [max] 旗艦質量 實時搜索增強、最強提示詞遵循 $0.07/MP (首個)
FLUX.2 [pro] 生產標準 零配置、高性價比、穩定輸出 $0.03/MP (首個)
FLUX.2 [flex] 開發調試 可調 steps/guidance、精細控制 $0.05/MP
FLUX.2 [dev] 開源部署 32B 參數開源權重 本地部署
FLUX.2 [klein] 輕量快速 4B/9B 參數、亞秒級推理 $0.014+/圖

🎯 接入建議: 對於大多數生產場景,我們建議通過 API易 apiyi.com 平臺接入 FLUX.2 Pro,該平臺提供統一的 OpenAI 兼容接口,無需處理複雜的官方 API 認證流程。


FLUX.2 Pro vs Max 核心差異

選擇 FLUX.2 Pro 還是 Max?這是開發者最常問的問題。下表詳細對比兩者差異:

flux-2-pro-max-api-integration-guide-zh-hant 图示

對比維度 FLUX.2 [pro] FLUX.2 [max] 勝出方
圖像質量 高質量、生產就緒 最高質量、專業級 Max
提示詞遵循 最強 (24B VLM) Max
實時搜索 ❌ 不支持 ✅ 支持 Max
生成速度 <10秒 <15秒 Pro
價格 $0.03/MP 起 $0.07/MP 起 Pro
穩定性 極高 Pro
參數可調 ❌ 固定最優 ❌ 固定最優 平局
適用場景 大規模生產、商業內容 高端創作、精細需求 按需選擇

選擇建議

選擇 FLUX.2 [pro] 的場景:

  • 電商產品圖批量生成
  • 社交媒體內容創作
  • 廣告素材大規模生產
  • 對成本敏感的項目
  • 需要穩定一致的輸出

選擇 FLUX.2 [max] 的場景:

  • 高端品牌廣告創意
  • 需要包含最新時事信息的圖像
  • 藝術創作和概念設計
  • 複雜場景的精確還原
  • 對質量要求極高的專業用途

FLUX.2 API 快速接入

方式一: 通過 API易 統一接口 (推薦)

API易平臺已上線 FLUX.2 Pro 和 FLUX.2 Max,支持 OpenAI 兼容格式調用:

import requests

# API易統一接口
base_url = "https://api.apiyi.com/v1"

def generate_image_flux2(prompt, model="flux.2-pro", width=1024, height=1024):
    """
    通過 API易 調用 FLUX.2 生成圖像

    Args:
        prompt: 圖像描述
        model: flux.2-pro 或 flux.2-max
        width: 圖像寬度 (16的倍數, 最大2048)
        height: 圖像高度 (16的倍數, 最大2048)
    """
    headers = {
        "Authorization": "Bearer YOUR_APIYI_KEY",
        "Content-Type": "application/json"
    }

    data = {
        "model": model,
        "prompt": prompt,
        "size": f"{width}x{height}",
        "response_format": "url"
    }

    response = requests.post(
        f"{base_url}/images/generations",
        json=data,
        headers=headers
    )

    result = response.json()
    return result["data"][0]["url"]


# 使用示例
image_url = generate_image_flux2(
    prompt="A professional product photo of a modern smartphone on marble surface, soft studio lighting, ultra detailed",
    model="flux.2-pro",
    width=1024,
    height=1024
)
print(f"生成圖像: {image_url}")

🚀 快速開始: 推薦使用 API易 apiyi.com 平臺快速接入 FLUX.2。該平臺提供開箱即用的 API 接口,無需複雜配置,支持 OpenAI SDK 直接調用。

方式二: BFL 官方 API

如需直接使用 Black Forest Labs 官方 API:

import requests
import time

class FLUX2Client:
    """FLUX.2 官方 API 客戶端"""

    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.bfl.ai/v1"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

    def generate(self, prompt, model="flux-2-pro", **kwargs):
        """
        生成圖像

        Args:
            prompt: 圖像描述
            model: flux-2-pro, flux-2-max, flux-2-flex
            **kwargs: width, height, seed, output_format, safety_tolerance
        """
        endpoint = f"{self.base_url}/{model}"

        data = {
            "prompt": prompt,
            "width": kwargs.get("width", 1024),
            "height": kwargs.get("height", 1024),
            "output_format": kwargs.get("output_format", "png")
        }

        # 添加可選參數
        if "seed" in kwargs:
            data["seed"] = kwargs["seed"]
        if "safety_tolerance" in kwargs:
            data["safety_tolerance"] = kwargs["safety_tolerance"]

        response = requests.post(endpoint, json=data, headers=self.headers)
        return response.json()

    def generate_with_flex(self, prompt, steps=50, guidance=4.5, **kwargs):
        """
        使用 FLUX.2 [flex] 生成 (支持參數調節)

        Args:
            prompt: 圖像描述
            steps: 採樣步數 1-50
            guidance: 引導係數 1.5-10
        """
        data = {
            "prompt": prompt,
            "steps": steps,
            "guidance": guidance,
            "width": kwargs.get("width", 1024),
            "height": kwargs.get("height", 1024)
        }

        response = requests.post(
            f"{self.base_url}/flux-2-flex",
            json=data,
            headers=self.headers
        )
        return response.json()


# 使用示例
client = FLUX2Client("YOUR_BFL_API_KEY")

# 使用 Pro 版本
result = client.generate(
    prompt="A serene Japanese garden with cherry blossoms",
    model="flux-2-pro",
    width=1536,
    height=1024
)
print(f"Pro 生成結果: {result}")

# 使用 Max 版本 (最高質量)
result_max = client.generate(
    prompt="A futuristic cityscape at night, neon lights, cyberpunk style, ultra detailed",
    model="flux-2-max",
    width=2048,
    height=2048
)
print(f"Max 生成結果: {result_max}")
查看異步批量生成完整代碼
import asyncio
import aiohttp
from typing import List, Dict

class AsyncFLUX2Client:
    """FLUX.2 異步客戶端,支持批量生成"""

    def __init__(self, api_key: str, base_url: str = "https://api.apiyi.com/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

    async def generate_single(self, session: aiohttp.ClientSession,
                              prompt: str, model: str = "flux.2-pro",
                              width: int = 1024, height: int = 1024) -> Dict:
        """異步生成單張圖像"""
        data = {
            "model": model,
            "prompt": prompt,
            "size": f"{width}x{height}",
            "response_format": "url"
        }

        async with session.post(
            f"{self.base_url}/images/generations",
            json=data,
            headers=self.headers
        ) as response:
            return await response.json()

    async def generate_batch(self, prompts: List[str],
                             model: str = "flux.2-pro",
                             max_concurrent: int = 5) -> List[Dict]:
        """
        批量生成圖像

        Args:
            prompts: 提示詞列表
            model: 模型版本
            max_concurrent: 最大併發數
        """
        semaphore = asyncio.Semaphore(max_concurrent)

        async def limited_generate(session, prompt):
            async with semaphore:
                return await self.generate_single(session, prompt, model)

        async with aiohttp.ClientSession() as session:
            tasks = [limited_generate(session, p) for p in prompts]
            results = await asyncio.gather(*tasks, return_exceptions=True)

        return results


async def main():
    client = AsyncFLUX2Client("YOUR_APIYI_KEY")

    prompts = [
        "A modern minimalist living room with natural lighting",
        "A vintage coffee shop interior with warm tones",
        "A futuristic office space with holographic displays",
        "A cozy bookstore with wooden shelves",
        "A high-tech laboratory with blue lighting"
    ]

    print("開始批量生成...")
    results = await client.generate_batch(prompts, model="flux.2-pro")

    for i, result in enumerate(results):
        if isinstance(result, Exception):
            print(f"圖像 {i+1} 生成失敗: {result}")
        else:
            print(f"圖像 {i+1}: {result['data'][0]['url']}")


if __name__ == "__main__":
    asyncio.run(main())

FLUX.2 API 核心參數詳解

flux-2-pro-max-api-integration-guide-zh-hant 图示

通用參數

參數 類型 必需 說明 示例值
prompt string ✅ 是 圖像描述,最長 32K tokens "A beautiful sunset…"
width int 圖像寬度,16的倍數 1024
height int 圖像高度,16的倍數 1024
seed int 隨機種子,用於復現結果 42
output_format string 輸出格式 jpeg/png "png"
safety_tolerance int 安全等級 0-5 2

分辨率配置建議

用途 推薦分辨率 像素數 Pro 價格 Max 價格
社交媒體方圖 1024×1024 1MP $0.03 $0.07
橫版海報 1536×1024 1.5MP $0.045 $0.10
豎版海報 1024×1536 1.5MP $0.045 $0.10
高清大圖 2048×2048 4MP $0.075 $0.16
超寬Banner 2048×768 1.5MP $0.045 $0.10

💡 成本優化: 對於預算敏感的項目,可以通過 API易 apiyi.com 平臺調用 FLUX.2 Pro,獲取更優惠的價格,適合批量生成場景。

FLUX.2 [flex] 獨有參數

FLUX.2 [flex] 版本支持精細的參數控制:

參數 類型 範圍 默認值 說明
steps int 1-50 50 採樣步數,越高質量越好
guidance float 1.5-10 4.5 引導係數,越高越貼近提示詞

Steps 參數效果:

Steps 質量 速度 適用場景
6 基礎 極快 快速草圖預覽
20 良好 迭代調試
50 最佳 標準 最終輸出

高級功能: 多圖參考與圖像編輯

FLUX.2 支持最多 10 張參考圖像輸入,實現風格遷移、角色一致性等高級功能:

import base64
import requests

def generate_with_references(prompt, reference_images, model="flux.2-pro"):
    """
    使用參考圖像生成

    Args:
        prompt: 圖像描述
        reference_images: 參考圖像URL或base64列表 (最多10張)
        model: 模型版本
    """
    headers = {
        "Authorization": "Bearer YOUR_APIYI_KEY",
        "Content-Type": "application/json"
    }

    # 處理參考圖像
    images = []
    for img in reference_images[:10]:  # 最多10張
        if img.startswith("http"):
            images.append({"type": "url", "url": img})
        else:
            images.append({"type": "base64", "data": img})

    data = {
        "model": model,
        "prompt": prompt,
        "reference_images": images,
        "size": "1024x1024"
    }

    response = requests.post(
        "https://api.apiyi.com/v1/images/generations",
        json=data,
        headers=headers
    )

    return response.json()


# 使用示例: 保持角色一致性
result = generate_with_references(
    prompt="Same character in a coffee shop, reading a book, warm lighting",
    reference_images=[
        "https://example.com/character_ref1.jpg",
        "https://example.com/character_ref2.jpg"
    ],
    model="flux.2-max"
)

圖像編輯功能

FLUX.2 支持基於自然語言的圖像編輯:

def edit_image(source_image, edit_prompt, model="flux.2-pro"):
    """
    編輯現有圖像

    Args:
        source_image: 源圖像URL或base64
        edit_prompt: 編輯指令
        model: 模型版本
    """
    headers = {
        "Authorization": "Bearer YOUR_APIYI_KEY",
        "Content-Type": "application/json"
    }

    data = {
        "model": model,
        "prompt": edit_prompt,
        "image": source_image,
        "mode": "edit"
    }

    response = requests.post(
        "https://api.apiyi.com/v1/images/edits",
        json=data,
        headers=headers
    )

    return response.json()


# 使用示例
result = edit_image(
    source_image="https://example.com/room.jpg",
    edit_prompt="Change the wall color to light blue, add plants near the window",
    model="flux.2-pro"
)

FLUX.2 提示詞最佳實踐

FLUX.2 的 Mistral-3 24B 視覺語言模型對提示詞有很強的理解能力。以下是優化提示詞的技巧:

提示詞結構模板

[主體描述] + [風格定義] + [光照/氛圍] + [細節要求] + [質量修飾]

優秀提示詞示例

場景 提示詞示例 關鍵技巧
產品攝影 "A sleek wireless headphone on white marble surface, professional studio lighting, product photography, sharp focus, 8K" 明確材質、光照、用途
人像藝術 "Portrait of a woman with braided hair, golden hour lighting, soft bokeh background, film grain, Hasselblad style" 指定相機風格、光照時段
建築可視化 "Modern minimalist house exterior, sunset light, architectural visualization, photorealistic, wide angle lens" 明確建築類型、視角
概念藝術 "Floating islands with waterfalls, fantasy world, epic scale, volumetric lighting, matte painting style" 描述獨特元素、風格

顏色控制技巧

FLUX.2 支持精確的十六進制顏色控制:

# 使用 hex 顏色代碼確保品牌色準確
prompt = """
A modern tech company logo mockup on business card,
primary color: #FF6B35 (orange),
secondary color: #1A1A2E (dark navy),
clean minimalist design, professional presentation
"""

成本優化與最佳實踐

定價計算示例

場景 分辨率 數量 Pro 成本 Max 成本 推薦
社交媒體配圖 1024×1024 100張 $3.00 $7.00 Pro
產品詳情頁 1536×1024 50張 $2.25 $5.00 Pro
高端廣告 2048×2048 20張 $1.50 $3.20 Max
快速原型 512×512 200張 $1.50 $3.50 Pro/Flex

成本優化策略

  1. 分辨率優化: 根據實際用途選擇合適分辨率,避免過度
  2. 模型選擇: 批量內容用 Pro,精品內容用 Max
  3. 預覽迭代: 使用 Flex 的低 steps 快速預覽,滿意後再高質量輸出
  4. 批量處理: 使用異步批量接口提高效率

💰 成本對比: 通過 API易 apiyi.com 平臺接入 FLUX.2,可獲得更靈活的計費方式。對於月調用量較大的用戶,平臺提供階梯優惠。


常見問題

Q1: FLUX.2 Pro 和 Max 如何選擇?

選擇依據主要是質量需求預算:

  • FLUX.2 Pro: 適合 90% 的生產場景,性價比高,輸出穩定
  • FLUX.2 Max: 適合高端創意、品牌廣告等對質量極致追求的場景

通過 API易 apiyi.com 平臺可以同時接入兩個版本,便於根據項目需求靈活切換。

Q2: 如何保證生成結果的一致性?

使用 seed 參數可以保證在相同提示詞下獲得一致的結果:

result = generate_image(
    prompt="A red apple on wooden table",
    seed=12345  # 固定種子
)

相同的 seed + prompt + 參數 = 相同的輸出圖像。

Q3: FLUX.2 支持中文提示詞嗎?

支持。FLUX.2 的 Mistral-3 VLM 具備多語言理解能力,中文提示詞可以正常使用。但建議:

  • 複雜場景使用英文提示詞效果更穩定
  • 中英混合使用時,核心描述用英文
  • 專業術語保持英文原詞
Q4: 生成失敗或超時怎麼處理?

建議的錯誤處理策略:

import time
from requests.exceptions import Timeout, RequestException

def generate_with_retry(prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            result = generate_image(prompt, timeout=60)
            return result
        except Timeout:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # 指數退避
            continue
        except RequestException as e:
            print(f"請求錯誤: {e}")
            break
    return None

API易平臺提供穩定的接口服務,超時問題較少出現。如遇問題可聯繫技術支持。

Q5: 如何獲取 FLUX.2 API 訪問權限?

有兩種方式:

  1. BFL 官方 API: 訪問 bfl.ai 註冊賬號
  2. API易平臺 (推薦): 訪問 apiyi.com 註冊,獲取統一 API Key,無需單獨申請 BFL 賬號

API易平臺提供免費測試額度,可快速驗證集成效果。


FLUX.2 API 接入總結

flux-2-pro-max-api-integration-guide-zh-hant 图示

FLUX.2 系列代表了當前圖像生成技術的前沿水平。本文介紹的核心要點:

要點 說明
模型選擇 Pro 適合生產,Max 適合高端創意
接入方式 推薦通過 API易 統一接口,兼容 OpenAI SDK
核心參數 prompt、size、seed 是最重要的三個參數
成本優化 根據用途選擇合適分辨率,批量用 Pro
高級功能 支持多圖參考、圖像編輯、精確顏色控制

推薦接入路徑:

  1. 訪問 apiyi.com 註冊賬號
  2. 獲取 API Key
  3. 使用本文代碼示例快速集成
  4. 根據效果調整提示詞和參數

通過 API易平臺,你可以快速接入 FLUX.2 Pro 和 Max,享受統一接口、穩定服務和靈活計費的優勢。


延伸閱讀:

  • FLUX.2 官方文檔: docs.bfl.ai
  • FLUX.2 模型介紹: bfl.ai/models/flux-2
  • FLUX.2 官方博客: bfl.ai/blog/flux-2

本文由 APIYI 技術團隊撰寫,如需瞭解更多 AI 模型 API 接入方案,歡迎訪問 apiyi.com

Similar Posts