image-gen
AI 图片生成器 — 基于 gpt-image-2 模型,支持文生图与图生图,开箱即用。
Install
npx skills add https://github.com/redfox-data/redfox-community/tree/main/skills/image-gen
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install redfox-data-redfox-community@llmmart
git clone https://github.com/redfox-data/redfox-community.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole redfox-data/redfox-community collection as a plugin from our marketplace. Git is the plain clone.
README
GPT-image2 / image-gen
简介
基于 OpenAI gpt-image-2 模型的 AI 图片生成器,支持文生图与图生图。
核心价值
- 文生图:输入提示词,生成全新高质量图片
- 图生图:上传参考图(最多 2 张) + 提示词,基于原图编辑生成
- 批量生成:单次最多 4 张(新接口上限)
- 参数可控:宽高比(16:9 / 9:16 / 1:1 等 13 种) + 分辨率档位(1k / 2k / 4k)
适用对象
- 🎨 设计师 — 快速生成创意概念图、Logo 设计
- 📱 内容运营 — 批量产出配图素材
- 🛍️ 电商卖家 — 生成产品展示图、场景图
功能特性
核心功能
- 文生图:输入提示词,gpt-image-2 自动生成 PNG 图片
- 图生图:上传参考图(最多 2 张),基于原图编辑生成
- 批量生成:单次最多 4 张,适合图标集、系列配图
- 宽高比可选:1:1 / 3:2 / 2:3 / 4:3 / 3:4 / 5:4 / 4:5 / 16:9 / 9:16 / 2:1 / 1:2 / 21:9 / 9:21
- 分辨率档位:1k(快) / 2k(默认) / 4k(高清,较慢)
- 任务管理:支持仅提交任务获取 taskId,稍后查询下载
密钥获取与安全说明
- 本技能需要使用环境变量:
REDFOX_API_KEY。 REDFOX_API_KEY由 红狐 hub (https://redfox.hk)提供。- 请前往 红狐 hub 注册账号,获取
REDFOX_API_KEY。 - 配置设备环境变量
REDFOX_API_KEY后使用本技能。 - 在提供密钥前,请先确认密钥来源、可用范围、有效期及是否支持重置/撤销。
- 禁止在代码、提示词、日志或输出文件中硬编码/明文暴露密钥。
使用指南
直接用自然语言描述你想要的图片即可。
常用说法速查
| 意图 | 示例话术 | 效果 |
|---|---|---|
| 文生图 | 「生成一只橘猫看窗外夕阳的图片」 | 提交任务,生成高质量图片 |
| 图生图 | 「把这张照片改成赛博朋克风格」 | 上传参考图进行风格迁移 |
| 竖版封面 | 「生成一张小红书封面,3:4 竖版」 | 使用 --size 3:4 生成竖构图 |
| 批量生成 | 「生成 4 张扁平风格图标」 | 一次生成多张风格一致的图片 |
使用场景
| 场景 | 角色 | 示例问法 | 收益 |
|---|---|---|---|
| 创意配图 | 内容运营 | 「生成一张文章封面图」 | 快速产出高质量配图 |
| Logo 设计 | 设计师 | 「生成一个极简风格的 Logo」 | 快速验证多种设计方案 |
| 产品展示 | 电商运营 | 「生成 4:3 的产品图」 | 零摄影成本的产品展示图 |
| 风格迁移 | 摄影师 | 「把这张照片转成水彩画风格」 | 自然语言驱动风格转换 |
Skill manifest
GPT-image2
调用 OpenAI 最新的 gpt-image-2 模型生成高质量图片。粘贴提示词就能用。
Skill 特色
- 支持命令行批量生成、参数化控制宽高比与分辨率档位
- 文生图 + 图生图双模式,
--image一个参数启用编辑模式(最多 2 张参考图)
能力概述
- 文生图:输入提示词,生成全新图片
- 图生图:上传参考图(最多 2 张) + 提示词,基于原图编辑生成
- 模型:gpt-image-2(OpenAI 最新图像模型)
- 接口:红狐新版
gptImage2Submit/gptImage2Result - 输出格式:PNG(新接口固定输出)
- 宽高比:
1:1/3:2/2:3/4:3/3:4/5:4/4:5/16:9(默认) /9:16/2:1/1:2/21:9/9:21 - 分辨率档位:
1k/2k(默认) /4k - 批量生成:单次最多 4 张(新接口上限)
- 兼容旧像素格式:仍接受
1792x1024等旧写法,脚本内部自动映射到宽高比 + 档位
使用方式
文生图 — 输入文字生成图片
# 基本生成(默认 16:9 + 2k)
python3 "$SKILL_PATH/assets/imagegen.py" "一只橘色的猫咪坐在窗台上看着窗外的夕阳"
# 横版 4k 高清
python3 "$SKILL_PATH/assets/imagegen.py" "futuristic city skyline" --size 16:9 --resolution 4k
# 竖版小红书封面(3:4 + 2k)
python3 "$SKILL_PATH/assets/imagegen.py" "product cover, minimal style" --size 3:4 --resolution 2k
# 方形 1k 快速档
python3 "$SKILL_PATH/assets/imagegen.py" "minimalist cat logo, flat design" --size 1:1 --resolution 1k
# 批量生成 4 张(新接口上限)
python3 "$SKILL_PATH/assets/imagegen.py" "icon set, flat style" -n 4
# 兼容旧像素写法(自动映射为 16:9 + 1k)
python3 "$SKILL_PATH/assets/imagegen.py" "cyberpunk street" --size 1792x1024
图生图 — 上传参考图编辑生成
# 单张参考图(自动上传 OSS → 提交任务)
python3 "$SKILL_PATH/assets/imagegen.py" "把猫咪改成白色,背景换成星空" --image ~/Pictures/cat.png
# 两张参考图(新接口最多支持 2 张)
python3 "$SKILL_PATH/assets/imagegen.py" "融合两张图的风格" --image ref1.png --image ref2.jpg
# 直接使用 URL 参考图(跳过上传步骤)
python3 "$SKILL_PATH/assets/imagegen.py" "把海报主体换成手表" --image "https://example.com/poster.jpg"
其他操作
# 仅提交任务(返回 taskId,不等待)
python3 "$SKILL_PATH/assets/imagegen.py" "complex scene" --no-download
# 查询已有任务结果
python3 "$SKILL_PATH/assets/imagegen.py" "" --task-id 5f100fcb8f3c4e3087c6aba93e121f7e
# 指定输出目录和文件名前缀
python3 "$SKILL_PATH/assets/imagegen.py" "illustration" -o ~/Pictures/AI --prefix artwork
参数说明
| 参数 | 说明 | 默认值 |
|---|---|---|
prompt |
生成/编辑提示词(必填,最多 500 字) | - |
--size |
宽高比(如 16:9);也兼容旧像素格式(如 1792x1024) |
16:9 |
--resolution |
分辨率档位:1k / 2k / 4k |
像素格式自动匹配;宽高比默认 2k |
-n, --count |
生成数量(1-4,新接口上限 4) | 1 |
--image |
参考图路径或 URL(可多次传入,最多 2 张) | - |
-o, --output-dir |
输出目录 | ~/Downloads/QoderImages |
--prefix |
文件名前缀 | image |
--no-download |
仅提交不等待 | - |
--task-id |
查询已有任务 | - |
--api-key |
指定 API Key | - |
已弃用参数(新接口不再支持,传入会被忽略并给出提示)
| 参数 | 说明 |
|---|---|
--quality |
用 --resolution 代替 |
--format |
新接口固定输出 PNG |
--bg / --background |
新接口不再支持背景控制 |
--compression |
新接口不再支持压缩比 |
--fidelity |
新接口不再支持保真度控制 |
依赖安装
| 依赖 | 安装命令 |
|---|---|
requests |
pip3 install requests |
首次使用
先配置 API Key,然后运行:
# 设置环境变量
export REDFOX_API_KEY=ak_你的密钥
# 运行
python3 "$SKILL_PATH/assets/imagegen.py" "一只橘色的猫咪"
前往 redfox.hk 注册获取 API Key。
⚠️ 新接口仅支持付费调用,账户免费积分无法抵扣本接口。若返回错误码
3203,请前往 充值页面 补充付费积分。
后续使用
前往 redfox.hk 注册账号获取自己的 API Token,三种配置方式任选其一:
| 配置方式 | 说明 | 命令 |
|---|---|---|
| 环境变量(推荐) | 设置一次,全局生效 | export REDFOX_API_KEY=ak_你的密钥 |
| 命令行参数 | 临时使用,单次生效 | python3 "$SKILL_PATH/assets/imagegen.py" "prompt" --api-key ak_你的密钥 |
| 配置文件 | 持久化存储,跨会话保留 | mkdir -p ~/.qoder/apis && echo '{"api_key":"ak_你的密钥"}' > ~/.qoder/apis/redfox.json |
接口规格(新)
提交任务
POST https://redfox.hk/story/api/parseWork/imageGen/gptImage2Submit
请求头:REDFOX_API_KEY: ak_xxx + Content-Type: application/json
请求体:
{
"prompt": "把这个海报的主体变为手表 并把文字都用中文",
"resolution": "2k",
"size": "16:9",
"n": 2,
"referenceImages": ["https://example.com/poster.jpg"]
}
响应:data.taskId 用于后续轮询。
查询结果
POST https://redfox.hk/story/api/parseWork/imageGen/gptImage2Result
请求体:{"taskId": "..."}
响应关键字段:
| 字段 | 说明 |
|---|---|
data.status |
completed / processing / queued / failed |
data.progress |
生成进度 0-100 |
data.imageUrls |
生成结果 URL 数组(数量与 n 一致) |
data.failReason |
失败原因(成功时为 null) |
data.model |
使用的模型(gpt-image-2) |
data.resolution / data.size |
实际使用的档位与宽高比 |
常见问题
Q:本 Skill 的特点是什么? A:命令行直接调用 gpt-image-2 模型,支持批量生成、宽高比与分辨率档位控制、图生图(最多 2 张参考图)。
Q:生成一张图片需要多久?
A:通常 10-60 秒,4k 档位或复杂场景可能更久。脚本会自动轮询等待并展示 progress。
Q:新的 resolution 与旧的 quality 有什么区别?
A:resolution 是分辨率档位(1k/2k/4k),直接决定输出图像的清晰度与生成耗时;旧的 quality 参数已弃用,传入会被忽略。
Q:为什么 --size 从像素改成了宽高比?
A:新接口 gptImage2Submit 的 size 字段就是宽高比(如 16:9)。为兼容旧调用,脚本仍接受 1792x1024 等像素写法,内部自动映射到宽高比 + 推荐档位。
Q:图生图能传几张参考图?
A:新接口最多 2 张。多次传入 --image 即可,超出部分会被截断并提示。
Q:为什么调用返回错误码 3203? A:新接口仅支持付费调用,账户免费积分不可抵扣。请前往 redfox.hk/dashboard/recharge 充值付费积分。
Q:如何获取 API Key? A:前往 redfox.hk 注册获取自己的 API Token。
Q:支持哪些图片格式作为参考图? A:支持 PNG、JPEG、WebP 格式的本地文件或 HTTP(S) URL。
Q:提示词有长度限制吗? A:提示词最多支持 500 字,超过会被阻断并提示精简。
Files (redfox-community)
-
assets
-
imagegen.py 17.7 KB
#!/usr/bin/env python3 """ Qoder Image Generator - 基于 gpt-image-2 的图片生成工具 对接红狐新版接口: SUBMIT: POST https://redfox.hk/story/api/parseWork/imageGen/gptImage2Submit RESULT: POST https://redfox.hk/story/api/parseWork/imageGen/gptImage2Result 新接口请求参数: prompt (String, 必填) resolution (String, 必填) 1k / 2k / 4k size (String, 必填) 宽高比:1:1 / 3:2 / 2:3 / 4:3 / 3:4 / 5:4 / 4:5 / 16:9 / 9:16 / 2:1 / 1:2 / 21:9 / 9:21 n (Integer, 必填) 生成数量,最大 4 referenceImages (Array, 必填) 参考图 URL 列表,最多 2 张(文生图传空数组) 新接口响应字段(data): taskId / status(completed|processing|failed) / progress(0-100) / imageUrls[] / failReason / model / resolution / size Usage: python3 imagegen.py "提示词" [options] python3 imagegen.py "修改提示词" --image ~/path/to/ref.png """ import argparse import json import os import sys import time from pathlib import Path import requests SUBMIT_URL = "https://redfox.hk/story/api/parseWork/imageGen/gptImage2Submit" RESULT_URL = "https://redfox.hk/story/api/parseWork/imageGen/gptImage2Result" UPLOAD_URL = "https://redfox.hk/story/api/parseWork/imageGen/uploadImage" CONFIG_DIR = Path.home() / ".qoder" / "apis" CONFIG_FILE = CONFIG_DIR / "redfox.json" ENV_KEY = "REDFOX_API_KEY" POLL_INTERVAL = 3 # seconds MAX_POLL_ATTEMPTS = 80 # max ~4 minutes # 新接口 size 支持的宽高比 VALID_ASPECTS = { "1:1", "3:2", "2:3", "4:3", "3:4", "5:4", "4:5", "16:9", "9:16", "2:1", "1:2", "21:9", "9:21", } VALID_RESOLUTIONS = {"1k", "2k", "4k"} # 兼容旧像素格式:像素尺寸 → (新接口 size 宽高比, 推荐 resolution 档位) LEGACY_SIZE_MAP = { "1024x1024": ("1:1", "1k"), "1024x1536": ("2:3", "1k"), "1536x1024": ("3:2", "1k"), "1792x1024": ("16:9", "1k"), "1024x1792": ("9:16", "1k"), "2048x2048": ("1:1", "2k"), "2048x1152": ("16:9", "2k"), "1152x2048": ("9:16", "2k"), } MAX_PROMPT_LENGTH = 500 MAX_REFERENCE_IMAGES = 2 MAX_COUNT = 4 GREEN = "\033[92m" YELLOW = "\033[93m" RED = "\033[91m" CYAN = "\033[96m" BOLD = "\033[1m" RESET = "\033[0m" def info(msg): print(f"{GREEN}[✓]{RESET} {msg}") def warn(msg): print(f"{YELLOW}[!]{RESET} {msg}") def error(msg): print(f"{RED}[✗]{RESET} {msg}") def step(msg): print(f"{CYAN}[→]{RESET} {msg}") def get_api_key(cli_key=None): """Get API key: CLI arg > env var > config file.""" if cli_key: return cli_key env_key = os.environ.get(ENV_KEY) if env_key: return env_key if CONFIG_FILE.exists(): try: data = json.loads(CONFIG_FILE.read_text()) key = data.get("api_key") if key: return key except (json.JSONDecodeError, OSError): pass return None def upload_image(api_key, image_path): """Upload a local image file to OSS, return the image URL.""" image_path = os.path.expanduser(image_path) if not os.path.isfile(image_path): error(f"Image file not found: {image_path}") return None ext = os.path.splitext(image_path)[1].lower() fmt_map = {".png": "png", ".jpg": "jpeg", ".jpeg": "jpeg", ".webp": "webp"} fmt = fmt_map.get(ext, "png") step(f"Uploading image: {image_path}") try: with open(image_path, "rb") as f: files = {"file": (os.path.basename(image_path), f)} data = {"format": fmt} headers = {"REDFOX_API_KEY": api_key, "X-API-KEY": api_key} resp = requests.post(UPLOAD_URL, files=files, data=data, headers=headers, timeout=60, verify=True) result = resp.json() except requests.exceptions.RequestException as e: error(f"Upload request failed: {e}") return None except json.JSONDecodeError: error(f"Upload returned invalid JSON: {resp.text[:200]}") return None code = result.get("code") if not str(code).startswith("2"): error(f"Upload failed (code {code}): {result.get('msg', '')}") return None data = result.get("data") or {} image_url = data.get("imageUrl") if not image_url: error("Upload succeeded but no imageUrl returned") return None info(f"Upload complete: {image_url}") return image_url def confirm_retry(): """询问用户是否需要重试。""" while True: answer = input(f"{YELLOW}[?]{RESET} 是否重试?(y/n): ").strip().lower() if answer in ('y', 'yes'): return True if answer in ('n', 'no'): return False def normalize_size(size_arg, resolution_arg): """把 CLI 传入的 --size 归一化为新接口的 (aspect, resolution)。 支持两种输入: 1. 像素格式(旧):1792x1024 → ("16:9", "1k") 2. 宽高比格式(新):16:9 → ("16:9", resolution_arg or "2k") """ size_str = (size_arg or "").strip() if size_str in LEGACY_SIZE_MAP: aspect, default_res = LEGACY_SIZE_MAP[size_str] resolution = (resolution_arg or default_res).strip().lower() if resolution not in VALID_RESOLUTIONS: error(f"Unsupported --resolution: {resolution}") sys.exit(1) return aspect, resolution if size_str in VALID_ASPECTS: resolution = (resolution_arg or "2k").strip().lower() if resolution not in VALID_RESOLUTIONS: error(f"Unsupported --resolution: {resolution}") sys.exit(1) return size_str, resolution error(f"Unsupported --size: {size_str}") print(f" 宽高比可选: {', '.join(sorted(VALID_ASPECTS))}") print(f" 兼容旧像素格式: {', '.join(sorted(LEGACY_SIZE_MAP.keys()))}") sys.exit(1) def submit_task(session, prompt, resolution, aspect, n, reference_images): """Submit image generation task via gptImage2Submit, return taskId.""" payload = { "prompt": prompt, "resolution": resolution, "size": aspect, "n": n, "referenceImages": reference_images or [], "source": "imageGen-GitHub", } try: resp = session.post(SUBMIT_URL, json=payload, timeout=30) result = resp.json() except requests.exceptions.RequestException as e: error(f"API request failed: {e}") return None except json.JSONDecodeError: error(f"API returned invalid JSON: {resp.text[:200]}") return None code = result.get("code") msg = result.get("msg", "") if not str(code).startswith("2"): error(f"Submit failed (code {code}): {msg}") return None data = result.get("data") or {} task_id = data.get("taskId") if not task_id: error("API did not return taskId") return None return task_id def poll_result(session, task_id): """Poll gptImage2Result until completed/failed/timeout, return imageUrls list.""" for attempt in range(1, MAX_POLL_ATTEMPTS + 1): try: resp = session.post(RESULT_URL, json={"taskId": task_id}, timeout=15) result = resp.json() except requests.exceptions.RequestException as e: warn(f"Poll request failed (attempt {attempt}): {e}") time.sleep(POLL_INTERVAL) continue except json.JSONDecodeError: warn(f"Invalid JSON response (attempt {attempt})") time.sleep(POLL_INTERVAL) continue code = result.get("code") if not str(code).startswith("2"): error(f"Query failed (code {code}): {result.get('msg', '')}") return None data = result.get("data") or {} status = data.get("status") if status == "completed": urls = data.get("imageUrls") or [] if isinstance(urls, str): urls = [urls] print() # 结束进度行 return urls elif status == "failed": reason = data.get("failReason") or "unknown" print() error(f"Generation failed: {reason}") return None else: # processing / pending progress = data.get("progress") elapsed = attempt * POLL_INTERVAL suffix = f" {progress}%" if isinstance(progress, int) else "" print(f"\r {CYAN}⏳ Generating...{suffix} ({elapsed}s){RESET}", end="", flush=True) time.sleep(POLL_INTERVAL) print() error("Timeout: task did not complete within expected time") return None def download_images(session, image_urls, output_dir, prefix="image"): """Download generated images to output directory.""" downloaded = [] total = len(image_urls) for i, url in enumerate(image_urls, 1): ext = ".png" url_path = url.split("?")[0] for fmt in [".png", ".jpg", ".jpeg", ".webp"]: if url_path.lower().endswith(fmt): ext = fmt break filename = f"{prefix}_{i}{ext}" if total > 1 else f"{prefix}{ext}" filepath = os.path.join(output_dir, filename) step(f"Downloading {i}/{total}: {filename}") try: resp = session.get(url, stream=True, timeout=120) resp.raise_for_status() total_size = int(resp.headers.get("content-length", 0)) dl = 0 with open(filepath, "wb") as f: for chunk in resp.iter_content(chunk_size=8192): if chunk: f.write(chunk) dl += len(chunk) if total_size > 0: pct = int(dl * 100 / total_size) bar = "█" * (pct // 5) + "░" * (20 - pct // 5) print(f"\r {bar} {pct}%", end="", flush=True) print() downloaded.append(filepath) except requests.exceptions.RequestException as e: error(f"Download failed: {e}") return downloaded def main(): parser = argparse.ArgumentParser( description="AI 图片生成器 - 基于 gpt-image-2(对接 gptImage2Submit/gptImage2Result 新接口)", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # 文生图(默认 16:9 + 2k) python3 imagegen.py "一只橘色的猫咪坐在窗台上看着窗外的夕阳" # 竖版 4k python3 imagegen.py "cyberpunk city" --size 9:16 --resolution 4k # 批量 4 张 python3 imagegen.py "icon set, flat style" -n 4 # 图生图(最多 2 张参考图) python3 imagegen.py "把猫咪改成白色,背景换成星空" --image ~/Pictures/cat.png # 兼容旧像素格式(自动映射为宽高比 + 分辨率档位) python3 imagegen.py "logo design" --size 1792x1024 """, ) parser.add_argument("prompt", help="图片生成/编辑提示词 (最多 500 字)") parser.add_argument("--api-key", help="API Key (不传则读取环境变量或配置文件)") parser.add_argument("-o", "--output-dir", help="输出目录 (默认 ~/Downloads/QoderImages)") parser.add_argument("-n", "--count", type=int, default=1, help=f"生成图片数量 (1-{MAX_COUNT}, 默认 1,新接口上限 4)") parser.add_argument("--size", default="16:9", help="图片宽高比 (默认 16:9,可选: " + ", ".join(sorted(VALID_ASPECTS)) + ");也兼容旧像素格式如 1792x1024") parser.add_argument("--resolution", default=None, choices=sorted(VALID_RESOLUTIONS), help="分辨率档位 1k/2k/4k(默认:像素格式跟随档位,宽高比格式默认 2k)") parser.add_argument("--image", action="append", default=None, help=f"参考图路径或 URL(可多次传入,最多 {MAX_REFERENCE_IMAGES} 张;启用图生图模式)") parser.add_argument("--no-download", action="store_true", help="仅提交任务并返回 taskId, 不等待结果") parser.add_argument("--task-id", help="直接查询已有任务的结果 (跳过提交)") parser.add_argument("--prefix", default="image", help="下载文件名前缀 (默认 image)") # 已弃用参数:新接口不再支持,仅为向后兼容 CLI 保留,接收后忽略 parser.add_argument("--quality", help="[已弃用] 新接口用 --resolution 表达档位,此参数被忽略") parser.add_argument("--format", dest="fmt", help="[已弃用] 新接口固定输出 PNG,此参数被忽略") parser.add_argument("--bg", "--background", dest="bg", help="[已弃用] 新接口不再支持 background,此参数被忽略") parser.add_argument("--compression", type=int, help="[已弃用] 新接口不再支持 outputCompression,此参数被忽略") parser.add_argument("--fidelity", help="[已弃用] 新接口不再支持 inputFidelity,此参数被忽略") args = parser.parse_args() # 弃用参数提示 deprecated = [] if args.quality: deprecated.append("--quality") if args.fmt: deprecated.append("--format") if args.bg: deprecated.append("--bg") if args.compression is not None: deprecated.append("--compression") if args.fidelity: deprecated.append("--fidelity") # 校验 count if args.count < 1 or args.count > MAX_COUNT: error(f"-n 取值范围 1-{MAX_COUNT}(新接口上限为 4)") sys.exit(1) # 校验 prompt 长度 if len(args.prompt) > MAX_PROMPT_LENGTH: error(f"提示词过长 ({len(args.prompt)} 字),请控制在 {MAX_PROMPT_LENGTH} 字以内") sys.exit(1) banner = f"""{CYAN}{BOLD} ╔══════════════════════════════════════╗ ║ Qoder Image Generator (API) ║ ║ AI 图片生成工具 · gpt-image-2 ║ ╚══════════════════════════════════════╝{RESET} """ print(banner) if deprecated: warn(f"以下参数在新接口已弃用,将被忽略: {', '.join(deprecated)}") # ── API Key ── api_key = get_api_key(cli_key=args.api_key) if not api_key: error("未找到 API Key,请设置环境变量 REDFOX_API_KEY 或使用 --api-key 参数") print(f" 获取 Key: https://redfox.hk/settings/api-keys?source=github") sys.exit(1) # ── Session(新接口鉴权头:REDFOX_API_KEY;同时兼容 X-API-KEY) ── session = requests.Session() session.verify = True session.headers.update({ "Content-Type": "application/json", "REDFOX_API_KEY": api_key, "X-API-KEY": api_key, }) # ── Mode: Query existing task ── if args.task_id: step(f"Querying task: {args.task_id}") image_urls = poll_result(session, args.task_id) if not image_urls: sys.exit(1) info(f"Generated {len(image_urls)} image(s)") output_dir = args.output_dir or str(Path.home() / "Downloads" / "QoderImages") os.makedirs(output_dir, exist_ok=True) downloaded = download_images(session, image_urls, output_dir, args.prefix) if downloaded: print(f"\n{GREEN}{BOLD}✓ Done!{RESET}") for f in downloaded: size_kb = os.path.getsize(f) / 1024 print(f" {f} ({size_kb:.1f} KB)") sys.exit(0) # ── Mode: Submit new task ── prompt = args.prompt.strip() if not prompt: error("提示词不能为空") sys.exit(1) # 归一化 size / resolution 到新接口格式 aspect, resolution = normalize_size(args.size, args.resolution) # 处理参考图 reference_images = [] if args.image: if len(args.image) > MAX_REFERENCE_IMAGES: warn(f"参考图数量超过上限,仅保留前 {MAX_REFERENCE_IMAGES} 张") for img in args.image[:MAX_REFERENCE_IMAGES]: if img.startswith("http://") or img.startswith("https://"): reference_images.append(img) else: url = upload_image(api_key, img) if not url: sys.exit(1) reference_images.append(url) step(f"Mode: 图生图 (referenceImages={len(reference_images)})") else: step("Mode: 文生图") step(f"Prompt: {prompt[:100]}{'...' if len(prompt) > 100 else ''}") step(f"Parameters: size={aspect}, resolution={resolution}, n={args.count}") while True: step("Submitting task...") task_id = submit_task(session, prompt, resolution, aspect, args.count, reference_images) if task_id: break if not confirm_retry(): sys.exit(1) info(f"Task submitted: {task_id}") if args.no_download: print(f"\n{GREEN}{BOLD}✓ Task submitted successfully{RESET}") print(f" taskId: {task_id}") print(f" 查询命令: python3 imagegen.py \"\" --task-id {task_id}") sys.exit(0) step("Waiting for generation...") image_urls = poll_result(session, task_id) if not image_urls: sys.exit(1) info(f"Generated {len(image_urls)} image(s)") output_dir = args.output_dir or str(Path.home() / "Downloads" / "QoderImages") os.makedirs(output_dir, exist_ok=True) downloaded = download_images(session, image_urls, output_dir, args.prefix) if downloaded: print(f"\n{GREEN}{BOLD}✓ Done!{RESET}") for f in downloaded: size_kb = os.path.getsize(f) / 1024 print(f" {f} ({size_kb:.1f} KB)") sys.exit(0) else: print(f"\n{RED}{BOLD}✗ Download failed{RESET}") sys.exit(1) if __name__ == "__main__": main()
-
-
README.en.md 3 KB
# GPT-image2 / image-gen --- ## Overview An AI image generator based on OpenAI's gpt-image-2 model, supporting text-to-image and image-to-image generation. **Core Value** - **Text-to-Image**: Enter a prompt to generate high-quality new images - **Image-to-Image**: Upload up to 2 reference images with a prompt for editing - **Batch Generation**: Up to 4 images per call (new interface limit) - **Fine-grained Control**: Aspect ratio (16:9 / 9:16 / 1:1, 13 options) + resolution tier (1k / 2k / 4k) **Target Users** - 🎨 **Designers** — Quickly generate creative concepts and logo designs - 📱 **Content Marketers** — Batch-produce image assets - 🛍️ **E-commerce Sellers** — Generate product and scene photography --- ## Features ### Core Features - **Text-to-Image**: Enter a prompt and gpt-image-2 generates PNG images - **Image-to-Image**: Upload up to 2 reference images for editing - **Batch Generation**: Up to 4 images per call, ideal for icon sets and series - **Aspect Ratio**: 1:1 / 3:2 / 2:3 / 4:3 / 3:4 / 5:4 / 4:5 / 16:9 / 9:16 / 2:1 / 1:2 / 21:9 / 9:21 - **Resolution Tier**: 1k (fast) / 2k (default) / 4k (high quality, slower) - **Task Management**: Submit-only mode with taskId for later query and download --- ## API Key Acquisition & Security - This skill requires the environment variable: `REDFOX_API_KEY`. - `REDFOX_API_KEY` is provided by [RedFoxHub](https://redfox.hk/settings/api-keys?source=github) (`https://redfox.hk`). - Please visit [RedFoxHub](https://redfox.hk?source=github) to register and obtain your `REDFOX_API_KEY`. - Configure the environment variable `REDFOX_API_KEY` on your device before using this skill. - Before providing your key, verify its source, available scope, validity period, and whether it supports reset/revocation. - Do not hardcode or expose the key in plaintext within code, prompts, logs, or output files. --- ## Usage Guide Simply describe the image you want in natural language. ### Quick Reference | Intent | Example | Result | |--------|---------|--------| | Text-to-Image | "Generate an image of an orange cat looking at the sunset" | Submits task and generates a high-quality image | | Image-to-Image | "Turn this photo into cyberpunk style" | Uploads reference for style transfer | | Portrait Cover | "Generate a 3:4 portrait cover for social media" | Uses --size 3:4 for vertical composition | | Batch Generation | "Generate 4 flat style icons" | Generates multiple style-consistent images at once | --- ## Use Cases | Scenario | Role | Example Prompt | Benefit | |----------|------|---------------|---------| | Creative visuals | Content marketer | "Generate an article cover image" | Quick high-quality illustrations | | Logo design | Designer | "Generate a minimalist logo" | Rapid design exploration | | Product display | E-commerce operator | "Generate a 4:3 product photo" | Zero photography cost | | Style transfer | Photographer | "Turn this photo into watercolor style" | Natural language style conversion | -
README.md 2.8 KB
# GPT-image2 / image-gen --- ## 简介 基于 OpenAI gpt-image-2 模型的 AI 图片生成器,支持文生图与图生图。 **核心价值** - **文生图**:输入提示词,生成全新高质量图片 - **图生图**:上传参考图(最多 2 张) + 提示词,基于原图编辑生成 - **批量生成**:单次最多 4 张(新接口上限) - **参数可控**:宽高比(16:9 / 9:16 / 1:1 等 13 种) + 分辨率档位(1k / 2k / 4k) **适用对象** - 🎨 **设计师** — 快速生成创意概念图、Logo 设计 - 📱 **内容运营** — 批量产出配图素材 - 🛍️ **电商卖家** — 生成产品展示图、场景图 --- ## 功能特性 ### 核心功能 - **文生图**:输入提示词,gpt-image-2 自动生成 PNG 图片 - **图生图**:上传参考图(最多 2 张),基于原图编辑生成 - **批量生成**:单次最多 4 张,适合图标集、系列配图 - **宽高比可选**:1:1 / 3:2 / 2:3 / 4:3 / 3:4 / 5:4 / 4:5 / 16:9 / 9:16 / 2:1 / 1:2 / 21:9 / 9:21 - **分辨率档位**:1k(快) / 2k(默认) / 4k(高清,较慢) - **任务管理**:支持仅提交任务获取 taskId,稍后查询下载 --- ## 密钥获取与安全说明 - 本技能需要使用环境变量:`REDFOX_API_KEY`。 - `REDFOX_API_KEY` 由 [红狐 hub](https://redfox.hk/settings/api-keys?source=github) (`https://redfox.hk`)提供。 - 请前往 [红狐 hub](https://redfox.hk?source=github) 注册账号,获取 `REDFOX_API_KEY`。 - 配置设备环境变量 `REDFOX_API_KEY` 后使用本技能。 - 在提供密钥前,请先确认密钥来源、可用范围、有效期及是否支持重置/撤销。 - 禁止在代码、提示词、日志或输出文件中硬编码/明文暴露密钥。 --- ## 使用指南 直接用自然语言描述你想要的图片即可。 ### 常用说法速查 | 意图 | 示例话术 | 效果 | |------|---------|------| | 文生图 | 「生成一只橘猫看窗外夕阳的图片」 | 提交任务,生成高质量图片 | | 图生图 | 「把这张照片改成赛博朋克风格」 | 上传参考图进行风格迁移 | | 竖版封面 | 「生成一张小红书封面,3:4 竖版」 | 使用 --size 3:4 生成竖构图 | | 批量生成 | 「生成 4 张扁平风格图标」 | 一次生成多张风格一致的图片 | --- ## 使用场景 | 场景 | 角色 | 示例问法 | 收益 | |------|------|---------|------| | 创意配图 | 内容运营 | 「生成一张文章封面图」 | 快速产出高质量配图 | | Logo 设计 | 设计师 | 「生成一个极简风格的 Logo」 | 快速验证多种设计方案 | | 产品展示 | 电商运营 | 「生成 4:3 的产品图」 | 零摄影成本的产品展示图 | | 风格迁移 | 摄影师 | 「把这张照片转成水彩画风格」 | 自然语言驱动风格转换 | -
SKILL.md 7.7 KB
--- name: image-gen description: AI 图片生成器 — 基于 gpt-image-2 模型,支持文生图与图生图,开箱即用。 --- # GPT-image2 调用 OpenAI 最新的 **gpt-image-2** 模型生成高质量图片。粘贴提示词就能用。 > **Skill 特色** > > - 支持命令行批量生成、参数化控制宽高比与分辨率档位 > - 文生图 + 图生图双模式,`--image` 一个参数启用编辑模式(最多 2 张参考图) --- ## 能力概述 - **文生图**:输入提示词,生成全新图片 - **图生图**:上传参考图(最多 2 张) + 提示词,基于原图编辑生成 - **模型**:gpt-image-2(OpenAI 最新图像模型) - **接口**:红狐新版 `gptImage2Submit` / `gptImage2Result` - **输出格式**:PNG(新接口固定输出) - **宽高比**:`1:1` / `3:2` / `2:3` / `4:3` / `3:4` / `5:4` / `4:5` / `16:9`(默认) / `9:16` / `2:1` / `1:2` / `21:9` / `9:21` - **分辨率档位**:`1k` / `2k`(默认) / `4k` - **批量生成**:单次最多 4 张(新接口上限) - **兼容旧像素格式**:仍接受 `1792x1024` 等旧写法,脚本内部自动映射到宽高比 + 档位 --- ## 使用方式 ### 文生图 — 输入文字生成图片 ```bash # 基本生成(默认 16:9 + 2k) python3 "$SKILL_PATH/assets/imagegen.py" "一只橘色的猫咪坐在窗台上看着窗外的夕阳" # 横版 4k 高清 python3 "$SKILL_PATH/assets/imagegen.py" "futuristic city skyline" --size 16:9 --resolution 4k # 竖版小红书封面(3:4 + 2k) python3 "$SKILL_PATH/assets/imagegen.py" "product cover, minimal style" --size 3:4 --resolution 2k # 方形 1k 快速档 python3 "$SKILL_PATH/assets/imagegen.py" "minimalist cat logo, flat design" --size 1:1 --resolution 1k # 批量生成 4 张(新接口上限) python3 "$SKILL_PATH/assets/imagegen.py" "icon set, flat style" -n 4 # 兼容旧像素写法(自动映射为 16:9 + 1k) python3 "$SKILL_PATH/assets/imagegen.py" "cyberpunk street" --size 1792x1024 ``` ### 图生图 — 上传参考图编辑生成 ```bash # 单张参考图(自动上传 OSS → 提交任务) python3 "$SKILL_PATH/assets/imagegen.py" "把猫咪改成白色,背景换成星空" --image ~/Pictures/cat.png # 两张参考图(新接口最多支持 2 张) python3 "$SKILL_PATH/assets/imagegen.py" "融合两张图的风格" --image ref1.png --image ref2.jpg # 直接使用 URL 参考图(跳过上传步骤) python3 "$SKILL_PATH/assets/imagegen.py" "把海报主体换成手表" --image "https://example.com/poster.jpg" ``` ### 其他操作 ```bash # 仅提交任务(返回 taskId,不等待) python3 "$SKILL_PATH/assets/imagegen.py" "complex scene" --no-download # 查询已有任务结果 python3 "$SKILL_PATH/assets/imagegen.py" "" --task-id 5f100fcb8f3c4e3087c6aba93e121f7e # 指定输出目录和文件名前缀 python3 "$SKILL_PATH/assets/imagegen.py" "illustration" -o ~/Pictures/AI --prefix artwork ``` ### 参数说明 | 参数 | 说明 | 默认值 | |------|------|--------| | `prompt` | 生成/编辑提示词(必填,最多 500 字) | - | | `--size` | 宽高比(如 `16:9`);也兼容旧像素格式(如 `1792x1024`) | `16:9` | | `--resolution` | 分辨率档位:`1k` / `2k` / `4k` | 像素格式自动匹配;宽高比默认 `2k` | | `-n, --count` | 生成数量(1-4,新接口上限 4) | `1` | | `--image` | 参考图路径或 URL(可多次传入,最多 2 张) | - | | `-o, --output-dir` | 输出目录 | `~/Downloads/QoderImages` | | `--prefix` | 文件名前缀 | `image` | | `--no-download` | 仅提交不等待 | - | | `--task-id` | 查询已有任务 | - | | `--api-key` | 指定 API Key | - | **已弃用参数(新接口不再支持,传入会被忽略并给出提示)** | 参数 | 说明 | |------|------| | `--quality` | 用 `--resolution` 代替 | | `--format` | 新接口固定输出 PNG | | `--bg` / `--background` | 新接口不再支持背景控制 | | `--compression` | 新接口不再支持压缩比 | | `--fidelity` | 新接口不再支持保真度控制 | ### 依赖安装 | 依赖 | 安装命令 | |------|----------| | `requests` | `pip3 install requests` | --- ## 首次使用 先配置 API Key,然后运行: ```bash # 设置环境变量 export REDFOX_API_KEY=ak_你的密钥 # 运行 python3 "$SKILL_PATH/assets/imagegen.py" "一只橘色的猫咪" ``` > 前往 [redfox.hk](https://redfox.hk/settings/api-keys?source=github) 注册获取 API Key。 > > ⚠️ 新接口仅支持**付费调用**,账户免费积分无法抵扣本接口。若返回错误码 `3203`,请前往 [充值页面](https://redfox.hk/dashboard/recharge) 补充付费积分。 --- ## 后续使用 前往 [redfox.hk](https://redfox.hk/settings/api-keys?source=github) 注册账号获取自己的 API Token,三种配置方式任选其一: | 配置方式 | 说明 | 命令 | |----------|------|------| | **环境变量**(推荐) | 设置一次,全局生效 | `export REDFOX_API_KEY=ak_你的密钥` | | **命令行参数** | 临时使用,单次生效 | `python3 "$SKILL_PATH/assets/imagegen.py" "prompt" --api-key ak_你的密钥` | | **配置文件** | 持久化存储,跨会话保留 | `mkdir -p ~/.qoder/apis && echo '{"api_key":"ak_你的密钥"}' > ~/.qoder/apis/redfox.json` | --- ## 接口规格(新) ### 提交任务 `POST https://redfox.hk/story/api/parseWork/imageGen/gptImage2Submit` 请求头:`REDFOX_API_KEY: ak_xxx` + `Content-Type: application/json` 请求体: ```json { "prompt": "把这个海报的主体变为手表 并把文字都用中文", "resolution": "2k", "size": "16:9", "n": 2, "referenceImages": ["https://example.com/poster.jpg"] } ``` 响应:`data.taskId` 用于后续轮询。 ### 查询结果 `POST https://redfox.hk/story/api/parseWork/imageGen/gptImage2Result` 请求体:`{"taskId": "..."}` 响应关键字段: | 字段 | 说明 | |------|------| | `data.status` | `completed` / `processing` / `queued` / `failed` | | `data.progress` | 生成进度 0-100 | | `data.imageUrls` | 生成结果 URL 数组(数量与 `n` 一致) | | `data.failReason` | 失败原因(成功时为 null) | | `data.model` | 使用的模型(`gpt-image-2`) | | `data.resolution` / `data.size` | 实际使用的档位与宽高比 | --- ## 常见问题 **Q:本 Skill 的特点是什么?** A:命令行直接调用 gpt-image-2 模型,支持批量生成、宽高比与分辨率档位控制、图生图(最多 2 张参考图)。 **Q:生成一张图片需要多久?** A:通常 10-60 秒,`4k` 档位或复杂场景可能更久。脚本会自动轮询等待并展示 progress。 **Q:新的 `resolution` 与旧的 `quality` 有什么区别?** A:`resolution` 是分辨率档位(`1k`/`2k`/`4k`),直接决定输出图像的清晰度与生成耗时;旧的 `quality` 参数已弃用,传入会被忽略。 **Q:为什么 `--size` 从像素改成了宽高比?** A:新接口 `gptImage2Submit` 的 `size` 字段就是宽高比(如 `16:9`)。为兼容旧调用,脚本仍接受 `1792x1024` 等像素写法,内部自动映射到宽高比 + 推荐档位。 **Q:图生图能传几张参考图?** A:新接口最多 2 张。多次传入 `--image` 即可,超出部分会被截断并提示。 **Q:为什么调用返回错误码 3203?** A:新接口仅支持付费调用,账户免费积分不可抵扣。请前往 [redfox.hk/dashboard/recharge](https://redfox.hk/dashboard/recharge) 充值付费积分。 **Q:如何获取 API Key?** A:前往 [redfox.hk](https://redfox.hk/settings/api-keys?source=github) 注册获取自己的 API Token。 **Q:支持哪些图片格式作为参考图?** A:支持 PNG、JPEG、WebP 格式的本地文件或 HTTP(S) URL。 **Q:提示词有长度限制吗?** A:提示词最多支持 500 字,超过会被阻断并提示精简。
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.