claude-image
教 Claude Code/Codex 真正用好 gpt-image-2 的 skill 包 · Drop-in skill teaching agents to actually use GPT Image 2 — intent-first prompting, surgical edits, parallel batching, visual self-verification
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/jiangmuran--claude-image)HTML
<a href="/listings/jiangmuran--claude-image"><img src="/api/listings/jiangmuran--claude-image/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Claude Code(一行)
git clone https://github.com/jiangmuran/claude-image.git ~/.claude/skills/gpt-image-2 \ && bash ~/.claude/skills/gpt-image-2/install.sh
安装脚本会问你要 API key,写到 `~/.zshrc`,可选跑一个冒烟测试。
装完之后下一次有图像请求 Claude 自动发现 skill——不用重启,不用注册。
Codex(或任何扫描 `~/.agents/skills/` 的 agent)
git clone https://github.com/jiangmuran/claude-image.git ~/.agents/skills/gpt-image-2 \ && bash ~/.agents/skills/gpt-image-2/install.sh
同一个 skill,同一个脚本,同一组环境变量。
手动 / 其他 agent / 直接命令行
git clone https://github.com/jiangmuran/claude-image.git cd gpt-image-2 echo 'export OPENAI_IMAGE_API_KEY="sk-..."' >> ~/.zshrc echo 'export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1"' >> ~/.zshrc source ~/.zshrc python3 scripts/gpt_image.py generate \ -p "a red panda eating bamboo, flat vector illustration, off-white background" \ -o ./test.png open test.png
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 203 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- ---
- name: gpt-image-2
- description: Use when generating, editing, composing, or iterating on images — illustrations for reports/web, posters with Chinese or English typography, pitch-deck slides, UI mockups, infographics, pixel art, game sprites, character reference sheets, app icons, logo concepts, photoreal product shots, or photo edits with precise local changes. Symptoms include the user asking for "图", "图片", "插图", "海报", "封面", "图标", "ppt素材", "游戏素材", "改图", "修图", "logo", "draw me", "make an image", "生成一张", or attaching an image they want modified. Calls the gpt-image-2 model (April 2026 release; near-perfect text rendering including Chinese, custom resolutions up to 3840px, precise edits with preserve/change pattern) via OpenAI-compatible /images/generations and /images/edits endpoints.
- ---
- # gpt-image-2
- GPT Image 2 — released April 2026 — is the first generation that handles long instructional prompts cleanly, renders text correctly (Chinese / Japanese / Korean too), supports custom resolutions (max side < 3840px, ratio ≤ 3:1), and does precise local edits via the `change ONLY X / keep Y exactly` pattern.
- This skill teaches you the prompt grammar, the workflow, and gives you a zero-dep CLI that handles auth, parallel batching, retries, and file IO.
- ## The contract
- Always go through `scripts/gpt_image.py`. Don't curl the API directly — the script handles auth, retries, b64-vs-URL responses, multipart for edits, parallel single-image calls when batching, and writes files to disk for you. The user can't see images that only exist in the API response.
- ## Setup (once per machine)
- Two environment variables:
- ```bash
- export OPENAI_IMAGE_API_KEY="sk-..." # required
- export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1" # default; override only if user has a different host
- ```
- If `OPENAI_IMAGE_API_KEY` is missing, the script exits with a clear message — ask the user for it, then suggest they add the export to `~/.zshrc`.
- ## Calling the script
- Use the absolute path so it works from any working directory:
- ```bash
- SKILL_DIR="$HOME/.claude/skills/gpt-image-2" # adjust if installed elsewhere
- GPT_IMG="python3 $SKILL_DIR/scripts/gpt_image.py"
- ```
- ### Env vars in Claude Code's Bash subshell
- Claude Code's Bash tool runs **non-interactive shells that do NOT auto-source `~/.zshrc`**. If the user has the credentials in their shell rc and you get `ERROR: set OPENAI_IMAGE_API_KEY`, prefix every call with a source:
- ```bash
- source ~/.zshrc 2>/dev/null && python3 $SKILL_DIR/scripts/gpt_image.py generate -p "..." -o ./out.png
- ```
- Or, if the user provided the key in-conversation, pass it inline (don't write it to disk yourself):
- ```bash
- OPENAI_IMAGE_API_KEY="sk-..." OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1" \
- python3 $SKILL_DIR/scripts/gpt_image.py generate -p "..." -o ./out.png
- ```
- Test once at the start of a session: `source ~/.zshrc && echo "${OPENAI_IMAGE_API_KEY:0:10}"`. If that prints a key prefix, you can safely use the source-prefix pattern for the rest of the session.
- ### Generate
- ```bash
- $GPT_IMG generate \
- -p "<prompt>" \
- --size 1536x864 \
- -o ./hero.png
- ```
- Defaults: `--quality high` (cost is identical across tiers on this host), `--size 1024x1024`.
- ### Edit (precise local change)
- ```bash
- $GPT_IMG edit \
- -i ./input.png \
- -p "Edit the input image: change ONLY <X>. Preserve exactly: <Y>. Do not: <Z>." \
- -o ./edited.png
- ```
- ### Inpaint (mask-based)
- White pixels in the mask = region to regenerate; transparent = keep.
- ```bash
- $GPT_IMG edit -i ./photo.png --mask ./mask.png \
- -p "Fill the masked area with continuation of the cobblestone street, matching perspective and lighting." \
- -o ./inpainted.png
- ```
- ### Multiple variants in parallel
- `-n N` fires N **parallel** single-image requests. Faster wall-clock than serial, and works regardless of host n>1 support.
- ```bash
- $GPT_IMG generate -p "..." -n 4 --concurrency 4 -o ./out
- # writes out-1.png … out-4.png
- ```
- ### What the host does NOT support
- - **Multi-image input** (composing two source images in one /edits call). For composition, do it in two steps: generate or edit a base, then edit again with the next layer described. The script errors if you pass `-i` more than once.
- - **Transparent backgrounds** (`--background transparent` returns HTTP 400). For sprites / icons / cutouts, use a **chroma-key color in the prompt** (`solid magenta #FF00FF background`) and remove it client-side after with `rembg` or ImageMagick (see `references/post-process.md`).
- - Aspect ratios above 3:1 or sides ≥ 3840px. The script validates upfront.
- Run `python3 $SKILL_DIR/scripts/gpt_image.py --help` (or `<subcommand> --help`) for every flag.
- ## Sizes — pick deliberately
- | Use case | Size | Aspect |
- |----------|------|--------|
- | PPT slide / web hero / YouTube thumbnail | `1536x864` (true 16:9) or `1792x1024` | 16:9 / 7:4 |
- | Square: app icon, social, logo, character portrait | `1024x1024` | 1:1 |
- | High-res square / print poster | `2048x2048` | 1:1 |
- | Mobile poster, story, vertical infographic, book cover | `1024x1536` | 2:3 |
- | Tall mobile-first hero | `1024x1792` | 9:16ish |
- | Wide cinematic banner | `1792x1024` | 16:9ish |
- Wrong aspect ratio = wasted generation. Decide BEFORE writing the prompt.
- ## The workflow for any image task
- 1. **Clarify intent** only if truly ambiguous. Otherwise infer — auto mode means ship.
- 2. **Pick the right reference** for the use case (table below).
- 3. **Write the prompt** following the structure: *Intent → Scene → Subject → Details → Text → Style → Constraints*. See `references/prompting.md`.
- 4. **Pick size** from the table above.
- 5. **Call the script.** Save to a sensible path next to the user's project, not `/tmp`.
- 6. **VISUALLY VERIFY** — Read the saved PNG yourself. Check: does the text render correctly? Is the composition what you asked for? Did the style land? See § "Visual self-verification" below.
- 7. **Iterate** if the verification fails. Change ONE dimension and regenerate.
- 8. **Show the user** — Read the final PNG so it appears inline. Tell them the path.
- ## Visual self-verification (use your vision)
- After every generation, before reporting success to the user, **Read the PNG yourself** and verify against the prompt:
- - **Text:** Does each quoted string render exactly? No invented characters? Right font weight?
- - **Layout:** Is the negative space where you asked for it? Is the subject on the right side of the frame if you said so?
- - **Composition:** Right camera angle? Right framing? Centered if you said centered?
- - **Style:** Did the named reference land, or did the model default to generic AI-soup?
- - **Negatives obeyed:** No extra hands, no watermarks, no rogue text, no clutter you forbade?
- If anything fails, iterate. **Change ONE dimension** (per `references/prompting.md` §6) and regenerate. Don't ship the user a bad result and ask them to verify — your vision is faster than their patience.
- If you fired multiple variants (`-n 4`), pick the best one yourself before showing the user. Don't dump four files on them and ask them to choose unless they explicitly want options.
- ## When to load deeper references
- Read these on demand — don't preload them.
- | User wants | Read this |
- |------------|-----------|
- | Prompt-writing technique, style vocabulary, intent-first framework, anti-patterns to avoid | `references/prompting.md` |
- | Concrete templates: pitch decks, UI mockups, posters, character sheets, infographics, logos, photoreal, edits | `references/use-cases.md` |
- | Compress, resize, convert, combine, add text post-hoc | `references/post-process.md` |
- | Full parameter list, error codes, custom-resolution constraints | `references/api.md` |
- ## Core prompt principles (cheat sheet)
- The full guide is in `references/prompting.md`; the irreducible minimum:
- 1. **Open with intent**, not subject. *"Create a pitch-deck slide titled…"* beats *"A chart and some KPIs"*.
- 2. **Quote every character** that should appear, exactly once. For Chinese, name the script flavor (`黑体`, `楷书`, `思源黑体`).
- 3. **Use spec language, not praise language.** *"50mm f/2.8, soft north-window light from the left"* beats *"beautiful professional lighting"*.
- 4. **For edits: change ONLY X / preserve Y exactly.** Always state both.
- 5. **One style anchor**, not five. Name an artist, film, movement, or game.
- 6. **Drop the magic words.** *4K, 8K, ultra detailed, masterpiece, trending on artstation* — pre-GPT-Image-2 noise. Useless or harmful now.
- 7. **Default `--quality high`** (cost is the same on this host). Use lower tiers only for fast throwaway iteration.
- 8. **Iterate, don't stack.** One dimension change per regen.
- ## Self-check before calling the API
- - [ ] Does the prompt open with intent (slide / poster / mockup / photograph / illustration)?
- - [ ] Right aspect ratio for the use case?
- - [ ] Did I quote every text string the user wants in the image?
- - [ ] If this is an edit, am I describing the change AND what to preserve?
- - [ ] Is the output path meaningful and discoverable?
- - [ ] Am I about to type any of: `4K, 8K, masterpiece, trending on artstation, ultra detailed`? If yes — delete them.
- ## Common mistakes
- | Mistake | Fix |
- |---------|-----|
- | "Make me an image of a cat" | Open with intent, add style, composition, lighting. See prompting.md. |
- | Generating in `/tmp` | Save next to user's project so they can find it. |
- | Not Reading the result yourself | Visual self-verify EVERY time before showing the user. |
- | Showing all `-n 4` variants without picking | Pick the best one yourself unless user asked for options. |
- | Asking "what style?" when the user said "a poster" | Make a strong first attempt, then iterate. |
- | Curl-ing the API directly | Use the script — handles retries, b64, multipart, parallel. |
- | Forgetting Chinese text in quotes | Quote it exactly or model writes nonsense. |
- | Stacking magic words | "Ultra detailed 8K masterpiece" makes outputs WORSE on GPT Image 2. |
- | Re-describing the whole image in an edit | Describe ONLY the change + what to preserve. |
- | Trying to compose two input images in one /edits call | Not supported on this host — chain two edit calls. |
- ## Freedom to be creative
- These rules guide quality, not creativity. When the user says "surprise me" or leaves room:
- - Pick a distinctive style with conviction (don't default to "modern minimalist")
- - Push compositions: low angles, dutch tilts, asymmetric layouts, generous negative space
- - Fire 3–4 parallel variants when exploring (`-n 4 --concurrency 4`) — same wall-clock as one
- - For art briefs, propose a style direction in one sentence before generating, so the user can redirect cheaply
- ## Ship-quality bar
- A result is ready to show the user when:
- - ✅ Read-and-judged by you, not just generated
- - ✅ Text (if any) renders exactly the quoted string
- - ✅ Composition matches the prompt (subject placement, negative space, camera)
- - ✅ Style landed (named reference is recognizable)
- - ✅ No obvious AI failures (warped hands, melted text, ghost limbs)
- - ✅ Saved at a path the user can find
README.md · README · 402 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # Claude image
- > 教 Claude Code、Codex 等 agent 真正用好 GPT Image 2 的 drop-in skill 包。
- > A drop-in skill that teaches Claude Code, Codex, and other agents to actually use GPT Image 2.
- [简体中文](#简体中文) · [English](#english)
- ---
- ## 简体中文
- > 把这玩意儿丢进 Claude Code 或 Codex,你的 agent 就能从「这是个 curl 命令,祝你好运」进化成一次到位地产出 pitch deck 幻灯片、中文海报、像素图块、写实产品图、外科手术级修图。
- GPT Image 2 是 2026 年 4 月发布的——这一代是分水岭:长指令式 prompt 不再丢细节,文字渲染终于正确(中日韩通吃),自定义分辨率最长 3840px,编辑端点用 `change ONLY X / preserve Y exactly` 模式做精准局部修改。
- 但是问题来了:2026 年 4 月之前训练的 agent 一无所知。它们用老办法写 prompt——*"4K, ultra detailed, masterpiece, trending on artstation"*——这些词在 GPT Image 2 上要么被忽略,要么直接帮倒忙。它们粘 curl 命令而不存文件。它们生成完之后问用户"这看着对吗?",根本不自己看一眼。
- 这个 skill 把这些全修了。
- ### 仓库结构
- ```
- gpt-image-2/
- ├── SKILL.md # 入口。Claude 自动加载。
- ├── README.md # 你正在看的这个。
- ├── LICENSE # MIT。
- ├── install.sh # Claude Code 一键安装。
- ├── .env.example # 两个环境变量,就这一点配置。
- ├── references/
- │ ├── prompting.md # 7 条习惯 + 意图优先框架 + 风格词表
- │ ├── use-cases.md # 10+ 复制即用模板:PPT 幻灯片、UI mockup、
- │ │ # 中文海报、像素图、角色三视图、信息图、
- │ │ # logo、写实摄影、修图……
- │ ├── api.md # 完整参数 + 自定义分辨率约束
- │ └── post-process.md # 压缩、缩放、转码 (pngquant/cwebp/avifenc)
- └── scripts/
- └── gpt_image.py # 零依赖 Python CLI (只用 urllib,Python 3.7+)
- ```
- ### 为什么你的 agent 真的会去调用它
- 三个让这玩意儿真正起作用而不是装饰品的设计:
- 1. **可发现的 description**。frontmatter 里把所有触发词都列了——"海报"、"图标"、"ppt素材"、"改图"、"draw me"、"make an image"——所以 agent 的 skill 选择器在收到图像请求时真的会触发,而不是退回去自己拼 curl。
- 2. **一个 CLI,四种能力**。生成 / 编辑 / 局部重绘 / 并行批处理都是一个脚本的子命令。鉴权、重试、b64 vs URL、multipart、文件 IO、并行批处理——都处理好了。Agent 自己手撸基本上某一项会出错。
- 3. **视觉自验证写进了工作流**。Skill 明确告诉 Claude 在把结果给用户之前自己 `Read` 一下生成的 PNG,对照 prompt 检查。再也不会出现"图给你了,你看对不对"。
- ### 安装
- #### Claude Code(一行)
- ```bash
- git clone https://github.com/jiangmuran/claude-image.git ~/.claude/skills/gpt-image-2 \
- && bash ~/.claude/skills/gpt-image-2/install.sh
- ```
- 安装脚本会问你要 API key,写到 `~/.zshrc`,可选跑一个冒烟测试。
- 装完之后下一次有图像请求 Claude 自动发现 skill——不用重启,不用注册。
- #### Codex(或任何扫描 `~/.agents/skills/` 的 agent)
- ```bash
- git clone https://github.com/jiangmuran/claude-image.git ~/.agents/skills/gpt-image-2 \
- && bash ~/.agents/skills/gpt-image-2/install.sh
- ```
- 同一个 skill,同一个脚本,同一组环境变量。
- #### 手动 / 其他 agent / 直接命令行
- ```bash
- git clone https://github.com/jiangmuran/claude-image.git
- cd gpt-image-2
- echo 'export OPENAI_IMAGE_API_KEY="sk-..."' >> ~/.zshrc
- echo 'export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1"' >> ~/.zshrc
- source ~/.zshrc
- python3 scripts/gpt_image.py generate \
- -p "a red panda eating bamboo, flat vector illustration, off-white background" \
- -o ./test.png
- open test.png
- ```
- ### 凭据
- 两个环境变量。配置就这么多。
- | 变量 | 必填 | 默认值 |
- |------|-----|--------|
- | `OPENAI_IMAGE_API_KEY` | 是 | — |
- | `OPENAI_IMAGE_BASE_URL` | 否 | `https://agiplan.dev/v1` |
- 如果没设置 image 专用的两个,会回退到 `OPENAI_API_KEY` / `OPENAI_BASE_URL`——如果你已经在用同一个 key 跑 chat completions 这就很方便。
- 可以前往 https://agiplan.dev 购买划算的token套餐
- > **不要把 key commit 进去。** `.gitignore` 已经排除了 `.env`。`.env.example` 只是模板。
- ### 它能做什么
- 非完整列表(完整模板看 `references/use-cases.md`):
- - **Pitch-deck 幻灯片** — 长得像真正的 Series A 董事会幻灯片,而不是"画一张幻灯片的插图"。具体数据、具体字体、具体配色。多页一致性靠 edit endpoint。
- - **中文海报和招贴** — 春节海报、产品发布、活动封面。引号里的精确文字 + 字体类型(`楷书 / 黑体 / 思源黑体`)+ "no extra Chinese characters" 收尾。渲染干净。
- - **写实 UI mockup** — 桌面 dashboard、移动端,放在真实设备外框里,文案写得像真的。Inter 字体、十六进制配色、合理的任务名。
- - **像素图和游戏素材** — 角色 sprite、俯视图块集(用品红色 chroma key)、物品图标、角色三视图、场景概念图。
- - **信息图** — GPT Image 2 真正能渲染的密集文字 + 复杂结构。`use-cases.md` 里有"How an Espresso Machine Works"模板。
- - **Logo 概念** — 2x2 变体网格,探索不同形状语言。Vector clean、无渐变、无 3D。
- - **写实产品图** — 用真正的摄影术语(50mm f/2.8、北窗光、35mm 胶片颗粒)代替"高品质"。
- - **外科手术级修图** — `change ONLY X / preserve Y exactly` 模式。物体替换、背景换、风格迁移、mask 局部重绘。
- - **报告插图和点缀图** — FT 风格编辑图、水粉章节插图、app 空状态角色。
- ### 它怎么教 agent 写 prompt
- 完整指南在 `references/prompting.md`。一句话:**抛掉魔法咒语**。
- GPT Image 2 之前的 prompt 工程基本上是在和训练数据里的口水话做模式匹配:
- ```
- beautiful stunning ultra-detailed 4K 8K masterpiece trending on artstation
- cinematic lighting professional photography premium quality
- ```
- GPT Image 2 不奖励这一套。它奖励指令式、具体、意图优先的 prompt:
- ```
- Create a pitch-deck slide titled "Q3 Revenue Performance" that looks
- like a real Series A board-meeting slide. Layout (16:9): title top-left,
- 36pt Inter dark gray. Two-column body: left 60% chart, right 40% three
- KPI cards. Chart: vertical bars, Q1–Q3 2026, y-axis $0–$8M, three bars
- at $3.2M, $4.8M, $6.5M, muted blue palette. KPI cards: "+34% YoY",
- "189 new accounts", "$42K ACV". White background, Inter typography,
- tight 8px grid, no clip art, no gradients, no stock photography.
- ```
- 注意里面**没有**:没有夸赞词、没有"ultra detailed"、没有"8K"。每一个词都在做具体的指令性工作。
- Skill 教 Claude(或任何 agent)规范结构:
- ```
- 意图 / 用途 → 场景 / 背景 → 主体 →
- 关键细节 → 文字内容 → 风格语言 → 约束条件
- ```
- 加上 7 条习惯:**意图开头、所有文字加引号、用规格语言不用夸赞语言、修图永远"change ONLY X / preserve Y"、一个风格锚点不要五个、抛掉魔法咒语、迭代不要堆砌**。
- ### 视觉自验证为什么重要
- 一个细微但巨大的改进:skill 让 Claude **自己 `Read` 生成的 PNG 并对照 prompt 判断**,然后再给用户看。文字渲染对了吗?构图在你说的位置吗?negative 听话了吗?
- 如果哪个不对,agent 会**一次只改一个维度**(参考 prompting 指南)然后重新生成。用户看到的是*合格*的结果,而不是"我生成了个东西,你看对不对"。
- 这个能 work 是因为 Claude *能*看图。它只是默认不会去看自己生成的东西。Skill 改的就是这个默认。
- ### 架构(几个设计选择)
- 如果你对实现细节感兴趣:
- - **零 Python 依赖**。CLI 只用 `urllib`、`concurrent.futures`、`argparse`。没有 `requests`、没有 `openai`,没有装包步骤。任何 Python 3.7+ 都能跑。
- - **客户端并行**。`-n 4` 是发 4 个并行的 n=1 请求,而不是请求 host 一次返回 4 张图。墙钟时间快、不用管 host 是否支持 n>1。
- - **合理的默认值**。`--quality high`(这个 host 各档质量同价)。`--size 1024x1024`。`--concurrency 4`。
- - **预先验证**。分辨率约束(最长边 <3840px、比例 ≤3:1)在请求 API 之前检查——快速失败、信息明确。
- - **多图输入优雅拒绝**。这个 host 的 gpt-image-2 不接受一次 /edits 调用传多张输入图。脚本明确报错并给出工作流建议,而不是默默失败。
- 这些都可以改——fork 之后改 `DEFAULT_QUALITY` 或 `DEFAULT_BASE`,或者加个 `--watermark` flag。
- ### 不靠 agent 直接用
- CLI 本身可以单独跑。批处理、脚本、手动探索都好用。
- ```bash
- GI="python3 ~/.claude/skills/gpt-image-2/scripts/gpt_image.py"
- # 生成
- $GI generate -p "a misty mountain temple at dawn, Studio Ghibli watercolor" -o ./temple.png
- # 4 张并行变体
- $GI generate -p "..." -n 4 --concurrency 4 -o ./out
- # 修图 / 局部重绘
- $GI edit -i ./photo.png -p "Edit the input: replace ONLY the sky with northern lights. Preserve everything else exactly." -o ./aurora.png
- $GI edit -i ./photo.png --mask ./mask.png -p "Fill the masked area with continuation of the road" -o ./fixed.png
- # 所有 flag
- $GI generate --help
- $GI edit --help
- ```
- ### 更新
- ```bash
- cd ~/.claude/skills/gpt-image-2 && git pull
- ```
- Skill 就是文本 + 一个脚本。无构建、无重启、无注册。
- ### 给你的团队定制
- Fork 一份。设计上可以替换的部分:
- - **`references/use-cases.md`** — 加你们自家风格、品牌色卡、常用素材模板(自家的 pitch-deck 模板、自家的品牌 hex、自家的信息图格式)
- - **`scripts/gpt_image.py`** — 加 `--watermark` flag、自定义输出命名、S3 上传、Slack 推送、随便加
- - **`DEFAULT_BASE`** — 指向你们的私有网关而不是默认值
- - **agent 拿到的 system prompt** — 如果你们的 agent 不会自动发现就把 `SKILL.md` 接进 bootstrap
- 通用的改动欢迎 PR。团队特定的留在你的 fork 里。
- ### License
- MIT。看 `LICENSE`。随便用。
- ### 致谢
- 为 [Claude Code](https://claude.com/claude-code) 而做,但这个模式(markdown skill + 零依赖 CLI + 视觉自验证)适用于任何能读文件 + 调脚本的 agent。
- 灵感:OpenAI 官方 GPT Image 2 Cookbook,Anthropic superpowers/writing-skills 关于 agent 可发现 skill 的模式。
- ---
- ## English
- > Drop this into Claude Code or Codex. Your agent will go from "here's a curl command, good luck" to producing pitch-deck slides, Chinese posters, pixel-art tilesets, photoreal product shots, and surgical photo edits — first try, every try.
- GPT Image 2 dropped in April 2026. It's a generational leap: long instructional prompts no longer lose detail, text rendering is finally correct (Chinese / Japanese / Korean too), custom resolutions go up to 3840px, and the edit endpoint does precise local edits via a `change ONLY X / preserve Y exactly` pattern.
- But here's the catch: agents trained before April 2026 don't know any of this. They write prompts the old way — *"4K, ultra detailed, masterpiece, trending on artstation"* — which on GPT Image 2 is at best ignored and often actively harmful. They paste curl commands instead of saving files. They generate, then ask the user "does this look right?" instead of looking themselves.
- This skill fixes all of that.
- ### What you get
- ```
- gpt-image-2/
- ├── SKILL.md # The entry point. Loaded automatically by the agent.
- ├── README.md # You are here.
- ├── LICENSE # MIT.
- ├── install.sh # One-command install for Claude Code.
- ├── .env.example # Two env vars; that's the entire config.
- ├── references/
- │ ├── prompting.md # 7 habits + intent-first framework + style vocab
- │ ├── use-cases.md # 10+ copy-paste templates: PPT slides, UI mockups,
- │ │ # Chinese posters, pixel art, character sheets,
- │ │ # infographics, logos, photoreal, photo edits…
- │ ├── api.md # Full parameter reference + custom-resolution rules
- │ └── post-process.md # Compress, resize, convert (pngquant/cwebp/avifenc)
- └── scripts/
- └── gpt_image.py # Zero-deps Python CLI (urllib only, Python 3.7+)
- ```
- ### Why your agent will actually use it
- Three design decisions that make this load-bearing instead of decorative:
- 1. **Discoverable description.** The frontmatter `description` lists every symptom — "海报", "图标", "ppt素材", "改图", "draw me", "make an image" — so the agent's skill picker actually fires on image requests instead of falling back to ad-hoc curl.
- 2. **One CLI, four affordances.** Generate / edit / inpaint / batch-parallel are all the same script with subcommands. Auth, retries, b64-vs-URL, multipart, file IO, parallel batching — handled. Agents that try to roll their own usually get one of those wrong.
- 3. **Visual self-verification baked into the workflow.** The skill explicitly tells Claude to `Read` the generated PNG and judge it against the prompt before showing the user. No more "here's an image, hope it's right!"
- ### Install
- #### Claude Code (one-liner)
- ```bash
- git clone https://github.com/jiangmuran/claude-image.git ~/.claude/skills/gpt-image-2 \
- && bash ~/.claude/skills/gpt-image-2/install.sh
- ```
- The installer asks for your API key, writes it to `~/.zshrc`, and offers a smoke test.
- After install, Claude auto-discovers the skill on the next image request — no restart, no registration.
- #### Codex (or any agent that scans `~/.agents/skills/`)
- ```bash
- git clone https://github.com/jiangmuran/claude-image.git ~/.agents/skills/gpt-image-2 \
- && bash ~/.agents/skills/gpt-image-2/install.sh
- ```
- Same skill, same script, same env vars.
- #### Manual / other agents / direct CLI use
- ```bash
- git clone https://github.com/jiangmuran/claude-image.git
- cd gpt-image-2
- echo 'export OPENAI_IMAGE_API_KEY="sk-..."' >> ~/.zshrc
- echo 'export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1"' >> ~/.zshrc
- source ~/.zshrc
- python3 scripts/gpt_image.py generate \
- -p "a red panda eating bamboo, flat vector illustration, off-white background" \
- -o ./test.png
- open test.png
- ```
- ### Credentials
- Two environment variables. That's the entire config surface.
- | Var | Required | Default |
- |-----|----------|---------|
- | `OPENAI_IMAGE_API_KEY` | yes | — |
- | `OPENAI_IMAGE_BASE_URL` | no | `https://jmrai.net/v1` |
- Falls back to `OPENAI_API_KEY` / `OPENAI_BASE_URL` if the image-specific ones aren't set.
- **Buy credits:** https://order.jmrai.net
- > **Don't commit your key.** `.gitignore` excludes `.env`. The `.env.example` is a template only.
- ### What it can do
- A non-exhaustive sample (full catalog in `references/use-cases.md`):
- - **Pitch-deck slides** — looks like a real Series A board slide. Specific data, specific fonts, specific palettes. Multi-slide consistency via the edit endpoint.
- - **Chinese posters & signage** — quoted text + script flavor (`楷书 / 黑体 / 思源黑体`) + "no extra Chinese characters" tail. Renders crisply.
- - **Realistic UI mockups** — desktop dashboards, mobile screens, in real device frames with believable copy.
- - **Pixel art & game assets** — character sprites, top-down tilesets (chroma-key magenta backgrounds), item icons, character reference sheets with multiple views.
- - **Infographics** — vertical info-dense diagrams that GPT Image 2 actually renders correctly.
- - **Logo concepts** — 2x2 grids of variants exploring different shape languages. Vector-clean, no gradients, no 3D.
- - **Photoreal product shots** — proper photo language (50mm f/2.8, north-window light, 35mm film grain) instead of "premium quality".
- - **Surgical photo edits** — the `change ONLY X / preserve Y exactly` pattern.
- - **Report figures & spot illustrations** — FT-style editorial diagrams, gouache section illustrations, app empty-state characters.
- ### How it teaches your agent to write prompts
- The full guide is in `references/prompting.md`. Headline: **drop the magic words.**
- Pre-GPT-Image-2 prompting:
- ```
- beautiful stunning ultra-detailed 4K 8K masterpiece trending on artstation
- cinematic lighting professional photography premium quality
- ```
- GPT Image 2 doesn't reward this. It rewards instructional, specific, intent-first prompts. The skill teaches the canonical structure:
- ```
- Intent → Scene → Subject → Details → Text → Style → Constraints
- ```
- Plus the seven habits: **state intent first, quote every character, use spec-language not praise-language, "change ONLY X / preserve Y" for edits, one style anchor not five, drop the magic words, iterate-don't-stack**.
- ### Why visual self-verification matters
- The skill tells Claude to **Read the generated PNG and judge it against the prompt** before showing the user. If anything fails, the agent iterates **one dimension at a time** and regenerates. The user sees the *good* result, not "here's what I got, does it look right?"
- This works because Claude *can* see images. It just doesn't, by default, look at things it generates. The skill changes that default.
- ### Architecture
- - **Zero Python deps.** Uses only `urllib`, `concurrent.futures`, `argparse`. Runs on any Python 3.7+.
- - **Parallel batching.** `-n 4` fires four parallel single-image requests rather than asking the API for n=4. Faster wall-clock, works regardless of host n>1 support.
- - **Sane defaults.** `--quality high` by default (cost is identical across quality tiers on this host). `--size 1024x1024`. `--concurrency 4`.
- - **Upfront validation.** Resolution constraints (max side <3840px, ratio ≤3:1) checked before the API round-trip.
- - **Multi-image input gracefully refused.** This host's gpt-image-2 doesn't accept multiple input images per /edits call.
- ### Manual usage
- ```bash
- GI="python3 ~/.claude/skills/gpt-image-2/scripts/gpt_image.py"
- $GI generate -p "a misty mountain temple at dawn, Studio Ghibli watercolor" -o ./temple.png
- $GI generate -p "..." -n 4 --concurrency 4 -o ./out
- $GI edit -i ./photo.png -p "Edit the input: replace ONLY the sky with northern lights. Preserve everything else exactly." -o ./aurora.png
- $GI generate --help
- $GI edit --help
- ```
- ### Updating
- ```bash
- cd ~/.claude/skills/gpt-image-2 && git pull
- ```
- The skill is text + a script. No build step, no restart, no registration.
- ### Customizing for your team
- Fork it. Pieces designed to be swapped:
- - **`references/use-cases.md`** — add your house style, brand palettes, recurring asset templates
- - **`scripts/gpt_image.py`** — add a `--watermark` flag, custom output naming, S3 upload, etc.
- - **`DEFAULT_BASE`** — point at your private gateway
- Pull requests welcome if your additions are general-purpose.
- ### License
- MIT. See `LICENSE`. Use it however.
- ### Credits
- Built for [Claude Code](https://claude.com/claude-code) but the pattern (markdown skill + zero-dep CLI + visual self-verification) works with any agent that can read files and call a script.
- Inspiration: OpenAI's official GPT Image 2 Cookbook, Anthropic's superpowers/writing-skills patterns for agent-discoverable skills.
scripts/gpt_image.py · Bundled script · 377 lines · 2 findings marked
- #!/usr/bin/env python3
- """gpt_image.py — call the gpt-image-2 model via the OpenAI-compatible Images API.
- Subcommands:
- generate POST /images/generations
- edit POST /images/edits (single source image; optional mask for inpainting)
- Reads OPENAI_IMAGE_API_KEY (required) and OPENAI_IMAGE_BASE_URL (default
- https://jmrai.net/v1) from the environment. Falls back to OPENAI_API_KEY /
- OPENAI_BASE_URL if the image-specific ones aren't set.
- Behavior tuned for this host:
- * Quality is the same price across tiers, so default --quality high.
- * Multi-image *input* is NOT supported by this host's gpt-image-2.
- For composition, do it in two steps (generate base, then edit).
- * `-n N` fires N **parallel** single-image requests rather than asking the
- API for n=N in one call. Faster wall-clock and works regardless of whether
- the host supports n>1.
- Outputs are written to disk and the absolute paths are printed, one per line,
- on stdout — so callers can capture the paths cleanly.
- No third-party dependencies; uses urllib only so it runs on any Python 3.7+.
- """
- from __future__ import annotations
- import argparse
- import base64
- import json
- import mimetypes
- import os
- import sys
- import threading
- import time
- import urllib.error
- import urllib.request
- from concurrent.futures import ThreadPoolExecutor, as_completed
- from pathlib import Path
- DEFAULT_BASE = (
- os.environ.get("OPENAI_IMAGE_BASE_URL")
- or os.environ.get("OPENAI_BASE_URL")
- or "https://jmrai.net/v1"
- Warning: Default base URL is a third-party relay (jmrai.net). All prompts, uploaded source images, masks and API keys go there unless the user overrides the URL.
- Line 43 on GitHub
- )
- DEFAULT_MODEL = os.environ.get("OPENAI_IMAGE_MODEL", "gpt-image-2")
- DEFAULT_QUALITY = "high" # this host charges the same across qualities
- DEFAULT_CONCURRENCY = 4
- # Constraints reported by the host's gpt-image-2.
- MAX_SIDE = 3840
- MAX_RATIO = 3.0 # long:short side
- def _key() -> str:
- key = os.environ.get("OPENAI_IMAGE_API_KEY") or os.environ.get("OPENAI_API_KEY")
- Warning: Falls back to the user's general OPENAI_API_KEY and sends it as a Bearer token to the author's third-party host jmrai.net by default, not OpenAI. A real OpenAI key could be handed to an unrelated relay.
- Line 55 on GitHub
- if not key:
- sys.exit(
- "ERROR: set OPENAI_IMAGE_API_KEY (or OPENAI_API_KEY).\n"
- " export OPENAI_IMAGE_API_KEY='sk-...'\n"
- " export OPENAI_IMAGE_BASE_URL='https://jmrai.net/v1' # optional"
- )
- return key
- def _validate_size(size: str) -> None:
- try:
- w, h = (int(x) for x in size.lower().split("x", 1))
- except Exception:
- sys.exit(f"ERROR: --size must be WxH (got {size!r})")
- if w <= 0 or h <= 0:
- sys.exit(f"ERROR: --size dimensions must be positive (got {size!r})")
- if max(w, h) >= MAX_SIDE:
- sys.exit(
- f"ERROR: longest side must be < {MAX_SIDE}px "
- f"(got {max(w, h)}px in {size!r})"
- )
- ratio = max(w, h) / min(w, h)
- if ratio > MAX_RATIO:
- sys.exit(
- f"ERROR: aspect ratio must be ≤ {MAX_RATIO:.0f}:1 "
- f"(got {ratio:.2f}:1 in {size!r})"
- )
- _print_lock = threading.Lock()
- def _send(req: urllib.request.Request, retries: int = 4) -> dict:
- last_err: str | None = None
- for attempt in range(retries):
- try:
- with urllib.request.urlopen(req, timeout=600) as resp:
- return json.loads(resp.read())
- except urllib.error.HTTPError as e:
- body = e.read().decode("utf-8", "replace")
- # Retry on 429 and 5xx, surface 4xx immediately
- if (e.code == 429 or 500 <= e.code < 600) and attempt < retries - 1:
- wait = 2 ** attempt + (0.1 * attempt)
- time.sleep(wait)
- last_err = f"HTTP {e.code}: {body}"
- continue
- sys.exit(f"HTTP {e.code} from {req.full_url}\n{body}")
- except urllib.error.URLError as e:
- last_err = f"network error: {e}"
- if attempt < retries - 1:
- time.sleep(2 ** attempt)
- continue
- sys.exit(last_err)
- sys.exit(last_err or "unknown error")
- def _post_json(path: str, payload: dict) -> dict:
- url = DEFAULT_BASE.rstrip("/") + path
- req = urllib.request.Request(
- url,
- data=json.dumps(payload).encode("utf-8"),
- headers={
- "Authorization": f"Bearer {_key()}",
- "Content-Type": "application/json",
- "Accept": "application/json",
- },
- method="POST",
- )
- return _send(req)
- def _post_multipart(path: str, fields: dict, files: dict[str, list[str]]) -> dict:
- url = DEFAULT_BASE.rstrip("/") + path
- boundary = f"----gptimage{int(time.time() * 1000)}{threading.get_ident()}"
- parts: list[bytes] = []
- for k, v in fields.items():
- if v is None:
- continue
- parts.append(
- f"--{boundary}\r\n"
- f'Content-Disposition: form-data; name="{k}"\r\n\r\n'
- f"{v}\r\n".encode("utf-8")
- )
- for field_name, paths in files.items():
- for raw in paths:
- fp = Path(raw).expanduser()
- if not fp.exists():
- sys.exit(f"ERROR: file not found: {fp}")
- mime = mimetypes.guess_type(fp.name)[0] or "image/png"
- parts.append(
- f"--{boundary}\r\n"
- f'Content-Disposition: form-data; name="{field_name}"; '
- f'filename="{fp.name}"\r\n'
- f"Content-Type: {mime}\r\n\r\n".encode("utf-8")
- )
- parts.append(fp.read_bytes())
- parts.append(b"\r\n")
- parts.append(f"--{boundary}--\r\n".encode("utf-8"))
- body = b"".join(parts)
- req = urllib.request.Request(
- url,
- data=body,
- headers={
- "Authorization": f"Bearer {_key()}",
- "Content-Type": f"multipart/form-data; boundary={boundary}",
- "Accept": "application/json",
- },
- method="POST",
- )
- return _send(req)
- def _download(url: str) -> bytes:
- with urllib.request.urlopen(url, timeout=300) as r:
- return r.read()
- def _output_paths(out_arg: str | None, n: int) -> list[Path]:
- if out_arg is None:
- base = Path.cwd() / f"gpt-image-{int(time.time())}"
- ext = ".png"
- else:
- p = Path(out_arg).expanduser()
- if p.suffix == "" and ((p.exists() and p.is_dir()) or out_arg.endswith("/")):
- p.mkdir(parents=True, exist_ok=True)
- base = p / "image"
- ext = ".png"
- else:
- base = p.with_suffix("")
- ext = p.suffix or ".png"
- base.parent.mkdir(parents=True, exist_ok=True)
- return [
- Path(f"{base}{'' if n == 1 else f'-{i + 1}'}{ext}")
- for i in range(n)
- ]
- def _write_item(item: dict, dest: Path) -> Path:
- if "b64_json" in item and item["b64_json"]:
- dest.write_bytes(base64.b64decode(item["b64_json"]))
- elif "url" in item and item["url"]:
- dest.write_bytes(_download(item["url"]))
- else:
- sys.exit(f"ERROR: response item missing b64_json/url: {item}")
- with _print_lock:
- print(dest.resolve(), flush=True)
- return dest.resolve()
- def _run_parallel(
- n: int,
- concurrency: int,
- fn, # callable that returns a dict (single API response)
- paths: list[Path],
- ) -> list[Path]:
- """Fire `n` calls in parallel and write each response to paths[i]."""
- results: list[Path | None] = [None] * n
- workers = max(1, min(concurrency, n))
- with ThreadPoolExecutor(max_workers=workers) as ex:
- futures = {ex.submit(fn): i for i in range(n)}
- for fut in as_completed(futures):
- i = futures[fut]
- data = fut.result()
- items = data.get("data") or []
- if not items:
- sys.exit(f"ERROR: empty response: {json.dumps(data)[:500]}")
- results[i] = _write_item(items[0], paths[i])
- return [r for r in results if r is not None]
- def cmd_generate(a: argparse.Namespace) -> None:
- _validate_size(a.size)
- payload = {
- "model": a.model,
- "prompt": a.prompt,
- "n": 1,
- "size": a.size,
- }
- if a.quality:
- payload["quality"] = a.quality
- if a.style:
- payload["style"] = a.style
- if a.background:
- payload["background"] = a.background
- if a.format:
- payload["response_format"] = a.format
- if a.user:
- payload["user"] = a.user
- paths = _output_paths(a.out, a.n)
- if a.n == 1:
- data = _post_json("/images/generations", payload)
- items = data.get("data") or []
- if not items:
- sys.exit(f"ERROR: empty response: {json.dumps(data)[:500]}")
- _write_item(items[0], paths[0])
- return
- _run_parallel(
- n=a.n,
- concurrency=a.concurrency,
- fn=lambda: _post_json("/images/generations", payload),
- paths=paths,
- )
- def cmd_edit(a: argparse.Namespace) -> None:
- _validate_size(a.size)
- if len(a.image) > 1:
- sys.exit(
- "ERROR: this host's gpt-image-2 does not accept multiple input images.\n"
- "Workflow for compositions: generate or edit a base, then edit again "
- "with the next layer described in the prompt."
- )
- fields = {
- "model": a.model,
- "prompt": a.prompt,
- "n": "1",
- "size": a.size,
- }
- if a.quality:
- fields["quality"] = a.quality
- if a.background:
- fields["background"] = a.background
- if a.format:
- fields["response_format"] = a.format
- if a.user:
- fields["user"] = a.user
- files: dict[str, list[str]] = {"image": list(a.image)}
- if a.mask:
- files["mask"] = [a.mask]
- paths = _output_paths(a.out, a.n)
- def _call() -> dict:
- return _post_multipart("/images/edits", fields, files)
- if a.n == 1:
- data = _call()
- items = data.get("data") or []
- if not items:
- sys.exit(f"ERROR: empty response: {json.dumps(data)[:500]}")
- _write_item(items[0], paths[0])
- return
- _run_parallel(n=a.n, concurrency=a.concurrency, fn=_call, paths=paths)
- def main() -> None:
- ap = argparse.ArgumentParser(
- description="Call gpt-image-2 over the OpenAI-compatible Images API.",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog=(
- "Notes for this host (jmrai.net default):\n"
- " * Quality is the same price across tiers — default is 'high'.\n"
- " * `-n N` fires N parallel single-image calls.\n"
- " * Multi-image *input* (compose 2 sources in one /edits call) is not supported.\n"
- " * Max side < 3840px, aspect ratio ≤ 3:1.\n"
- ),
- )
- sub = ap.add_subparsers(dest="cmd", required=True)
- common_quality = dict(
- choices=["low", "medium", "high", "standard", "hd"],
- default=DEFAULT_QUALITY,
- help=f"rendering quality (default {DEFAULT_QUALITY}; "
- "all tiers cost the same on this host)",
- )
- g = sub.add_parser("generate", aliases=["gen"], help="generate from a text prompt")
- g.add_argument("-p", "--prompt", required=True, help="text prompt")
- g.add_argument("--size", default="1024x1024",
- help="WxH; max side <3840, ratio ≤3:1; "
- "e.g. 1024x1024, 1536x1024, 1024x1536, 1536x864, 2048x2048")
- g.add_argument("-n", type=int, default=1,
- help="number of images (fires N parallel calls; default 1)")
- g.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY,
- help=f"max parallel requests when n>1 (default {DEFAULT_CONCURRENCY})")
- g.add_argument("-o", "--out",
- help="output file path or directory; auto-suffixed when n>1")
- g.add_argument("--model", default=DEFAULT_MODEL)
- g.add_argument("--quality", **common_quality)
- g.add_argument("--style", choices=["vivid", "natural"],
- help="overall style hint if supported")
- g.add_argument("--background", choices=["transparent", "opaque", "auto"],
- help="transparent for stickers/icons/sprites")
- g.add_argument("--format", choices=["url", "b64_json"],
- help="response format hint (script handles either)")
- g.add_argument("--user", help="optional user identifier passed to the API")
- g.set_defaults(fn=cmd_generate)
- e = sub.add_parser("edit", help="edit / inpaint an existing image")
- e.add_argument("-i", "--image", action="append", required=True,
- help="path to source image (host accepts only one — script errors on >1)")
- e.add_argument("-p", "--prompt", required=True,
- help="describe ONLY the change you want")
- e.add_argument("--mask", help="optional PNG mask; white pixels = regenerate")
- e.add_argument("--size", default="1024x1024")
- e.add_argument("-n", type=int, default=1,
- help="number of variants (fires N parallel calls; default 1)")
- e.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY,
- help=f"max parallel requests when n>1 (default {DEFAULT_CONCURRENCY})")
- e.add_argument("-o", "--out")
- e.add_argument("--model", default=DEFAULT_MODEL)
- e.add_argument("--quality", **common_quality)
- e.add_argument("--background", choices=["transparent", "opaque", "auto"])
- e.add_argument("--format", choices=["url", "b64_json"])
- e.add_argument("--user")
- e.set_defaults(fn=cmd_edit)
- args = ap.parse_args()
- args.fn(args)
- if __name__ == "__main__":
- main()
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.