Generate a complete cover containing the book title and pen name based on the book title and genre, so readers can tell the genre and atmosphere at a glance.
Generation pathways
- Codex built-in (preferred): when the current Codex CLI session can call
$imagegen/image_gen, directly call the tool to generate and save, with no need forOPENAI_API_KEYorGPT_IMAGE_API_KEY, and do not runcurl。 - API fallback: use only when the session has no built-in tool or the user explicitly specifies the API; requires
GPT_IMAGE_API_KEY. A missing tool does not mean the Codex subscription does not support image generation; when a built-in call fails, report the error first and do not silently switch to a potentially billable API.
Output parameters and API fallback environment variables
| Variable | Required | Default | Description |
|---|---|---|---|
GPT_IMAGE_API_KEY |
Required for API fallback | — | API Key for OpenAI or a compatible proxy; not needed for the Codex built-in pathway |
GPT_IMAGE_BASE_URL |
https://api.openai.com/v1 |
Change this when using a compatible proxy | |
GPT_IMAGE_MODEL |
gpt-image-2 |
Override only when testing a new model | |
GPT_IMAGE_SIZE |
1024x1536 |
Request size for API fallback: Tomato 3:4→768x1024, default 2:3→1024x1536. The actual size is subject to the generated image result; the fixed upload pixels are guaranteed by the "Export platform upload size" step |
|
UPLOAD_SIZE |
— | Platform fixed upload pixels (Tomato 600x800); once set, the "Export platform upload size" step center-crops + scales to the upload version (no distortion, independent of the generated image size) |
|
BOOK_DIR |
✅ | — | Output directory, recommended ./covers/<书名> |
REF_IMAGE |
— | Local path or URL of the reference image; the built-in pathway first loads the image into the session, and the API fallback uses images/edits image-to-image |
Generation workflow
Step 1: Collect information
Required: book title, author name (pen name), target platform, output directory BOOK_DIR. The directory is recommended to be ./covers/<书名>; the API fallback passes it in via environment variables, and the built-in pathway directly uses the directory determined for this session. When asking the author, say "Where should the cover be saved? Default ./covers/<书名>".
Optional: reference image REF_IMAGE(local path or URL), style preference, size; for how to use the reference image, see the corresponding pathway in Step 4.
The book title and pen name are required cover information: if either is missing, first ask the author to complete it using the questioning method available in the host; do not fabricate or leave it blank.
Determine the cover size according to the target platform: Tomato uploads 600×800, with a ratio of 3:4; if the generated image ratio does not match, the platform may crop again and cut off the book title or pen name.
| Platform | Upload size | Ratio | Generate GPT_IMAGE_SIZE(as much as possible) |
|---|---|---|---|
| Tomato Novel | 600×800 | 3:4 | 768x1024 |
| Other platforms (default portrait) | According to platform specifications | 2:3 | 1024x1536 |
The built-in pathway writes the target ratio into the prompt; the API fallback then export GPT_IMAGE_SIZE. When the platform has fixed upload pixels, set UPLOAD_SIZE(Tomato 600x800), and in Step 5 center-crop and scale to the exact size. For platforms and genre styles, see references/cover-styles.md。
Step 2: Genre Determination
Scan the keywords in the book title (and the synopsis if necessary), and select the genre against the "Genre Inference Rules" table in references/cover-styles.md .
- Single genre match → use it directly
- Multiple genre matches → pick one by priority: Xianxia > Western Fantasy > Ancient Romance > Modern Romance > Urban > Mystery > Sci-Fi > Historical > Supernatural > Light Novel
- Zero matches → default to
都市
Step 3: Build the Prompts
Prompt = Text Layer + Style Layer + Scene Layer. Write design instructions in English; keep the book title and pen name in the original text provided by the author.
Text Layer: Font design for the book title + author name
Include the Chinese book title and author name directly in the prompt; GPT-Image-2 can render them directly.Focus on describing the font style:
Title text '书名' at top center in [书名字体风格].
Author name '作者名' at bottom center in [作者名字体风格].
Book title font style
| Genre | Description keywords |
|---|---|
| Fantasy/Xianxia | bold golden brush calligraphy with metallic glow and sharp strokes |
| Urban | modern bold sans-serif with metallic silver finish |
| Ancient Romance/Palace Intrigue | elegant golden traditional Kai script with ornate decoration |
| Modern Romance/Sweet Romance | soft rounded handwritten style in white with pink glow |
| Mystery/Deduction | distorted bold cracked letters in blood red |
| Sci-Fi/Apocalypse | neon glowing futuristic font in electric blue |
| Western Fantasy | metallic embossed fantasy lettering with glow effect |
| Historical/Military | heavy stone-carved seal script in deep red |
| Supernatural/Horror | eerie dripping handwritten font in sickly green |
| Light Novel | colorful cartoon outlined bubbly font |
Author name font style (key point: the author name must be carefully designed, not just "small text")
Author name specificationFont, color, and decorative elements, echoing the book title style, staying clearly readable without stealing focus.
| Genre | Author name style prompt |
|---|---|
| Fantasy/Xianxia | small refined white serif text with faint golden glow, flanked by delicate cloud-scroll ornaments on both sides, resting on a thin horizontal gold line |
| Urban | small clean white modern text with subtle drop shadow, positioned above a thin silver horizontal divider line |
| Ancient Romance/Palace Intrigue | small elegant dark red traditional text inside a thin golden rectangular border frame with corner decorations |
| Modern Romance/Sweet Romance | small soft pink-white handwritten text with a tiny heart motif on the left side, light sparkle effect |
| Mystery/Deduction | small pale grey text with slight blur effect, almost hidden in the shadows, a thin cracked line underneath |
| Sci-Fi/Apocalypse | small crisp white monospace text with subtle cyan scanline overlay, flanked by small geometric brackets |
| Western Fantasy | small bronze medieval script text with aged parchment texture, enclosed in a small decorative shield or banner shape |
| Historical/Military | small dignified white Song typeface text above a double horizontal line in dark red |
| Supernatural/Horror | small faded grey-green text slightly tilted, with a thin dripping ink line above |
| Light Novel | small playful rounded white text with pastel color outline, tiny star decorations on both sides |
General rules for the author name:
- Size:
small(not too large to steal focus from the book title, nor too small to be unreadable) - Position:
at bottom center, keeping appropriate spacing from the bottom of the image - Must have decorative elements: at least one of lines/borders/small icons/light effects
- The color contrasts with the background but is not harsh
Style Layer: Platform style
From references/cover-styles.md , select the keyword string corresponding to the target platform in the "Platform Style" section.
Scene Layer: Genre + Composition
From references/cover-styles.md , read the style tags, colors, characters, and background descriptions corresponding to the genre.
Composition variants (output 2-3 options the first time):
| Option | Composition | Suitable genres |
|---|---|---|
| A | Character close-up + scene | Universal for all genres |
| B | Full-body figure + dynamic pose | Fantasy, Urban, Western Fantasy |
| C | Pure scene/atmosphere image | Mystery, Sci-Fi, Historical |
Full prompt template
Chinese web novel cover design, [平台风格].
Title text '{书名}' at top center in [书名字体风格].
Author name '{作者名}' at bottom center in [作者名字体风格 — 从上表选择].
[题材风格标签]. [人物描述]. [背景描述].
[色彩指令]. [光效指令].
Professional book cover, high detail digital painting, portrait [平台比例:番茄=3:4,默认=2:3] ratio, keep title and author name inside the central safe area away from edges (inner ~85%), no watermark
Prompt techniques (field-tested)
- The more specific the character description, the better: specify every dimension—clothing, pose, hairstyle, expression, props
- Background layering: foreground (character) → midground (scene) → background (atmosphere)
- Light effects mean specifying the light source direction + color (e.g.,
dramatic golden light from above) - Use
digital painting styleinstead ofphoto, to avoid a photorealistic look
Step 4: Generate and save
Codex built-in ImageGen (preferred)
- Call with the complete prompt from Step 3:
image_gen. Write the aspect ratio and safe area into the prompt; do not passGPT_IMAGE_MODEL、GPT_IMAGE_SIZE、response_formatand other API parameters. - When there is
REF_IMAGE, for local files first load them into the session with an image viewing tool; for URLs, download first and then load. State whether it is an editing target or a style reference, and list what must be preserved. - Call once separately for each composition plan. First create
BOOK_DIR/封面/, then copy the image returned by the tool as封面_vN.png,Nwith auto-increment and without overwriting older versions; keep the$CODEX_HOME/generated_images/original file, and at the same time save a same-named.prompt.txt, and if there is a reference image, also save.ref.txt. Confirm the image is readable, and pass the original image's absolute path to Step 5.
API fallback
gpt-image-2 returns base64; the request body does not include response_format。$PROMPT Use the complete prompt assembled in Step 3.
Choose one of the two calling methods: if REF_IMAGE is not set → use "text-to-image"; if set → use "image-to-image".
Text-to-image (default)
set -euo pipefail
: "${GPT_IMAGE_API_KEY:?请设置 export GPT_IMAGE_API_KEY=你的key}"
: "${PROMPT:?请先 export PROMPT=构建提示词步骤拼好的完整提示词}"
BASE_URL="${GPT_IMAGE_BASE_URL:-https://api.openai.com/v1}"
MODEL="${GPT_IMAGE_MODEL:-gpt-image-2}"
SIZE="${GPT_IMAGE_SIZE:-1024x1536}"
BOOK_DIR="${BOOK_DIR:?请先 export BOOK_DIR=./covers/<书名>}"
mkdir -p "$BOOK_DIR/封面"
# 自增版本号,避免覆盖之前生成的封面
i=1
while [ -f "$BOOK_DIR/封面/封面_v${i}.png" ]; do i=$((i+1)); done
OUT="$BOOK_DIR/封面/封面_v${i}.png"
RESP=$(mktemp)
trap 'rm -f "$RESP"' EXIT
# 用 jq 拼 JSON 体,避免 PROMPT 里的引号/换行/中文把 shell 字符串撑破
BODY=$(jq -n \
--arg m "$MODEL" \
--arg p "$PROMPT" \
--arg s "$SIZE" \
'{model:$m, prompt:$p, size:$s}')
curl -fsS --max-time 180 --retry 2 --retry-delay 5 \
"$BASE_URL/images/generations" \
-H "Authorization: Bearer $GPT_IMAGE_API_KEY" \
-H "Content-Type: application/json" \
-d "$BODY" > "$RESP"
# API 出错时早退,避免把 error JSON 当成 base64 写成损坏 PNG
if jq -e '.error' "$RESP" >/dev/null 2>&1; then
echo "API error:" >&2
jq '.error' "$RESP" >&2
exit 1
fi
# `// empty` 让缺失字段输出空串而非 "null",配合下面的 -s 检查避免写出 3 字节假 PNG
jq -er '.data[0].b64_json // empty' "$RESP" | base64 --decode > "$OUT"
[ -s "$OUT" ] || { echo "empty or malformed output: $OUT" >&2; head -c 300 "$RESP" >&2; exit 1; }
# 落地提示词副本,方便迭代时基于上一次微调
printf '%s\n' "$PROMPT" > "${OUT%.png}.prompt.txt"
file "$OUT"
ls -lt "$BOOK_DIR/封面/"
Image-to-image (when a reference image is provided)
The following /v1/images/edits command uploads the local image via multipart/form-data , without adding Content-Type: application/json. Use --form-stringfor text fields, and use -F image=@path。
set -euo pipefail
: "${GPT_IMAGE_API_KEY:?请设置 export GPT_IMAGE_API_KEY=你的key}"
: "${PROMPT:?请先 export PROMPT=构建提示词步骤拼好的完整提示词}"
BASE_URL="${GPT_IMAGE_BASE_URL:-https://api.openai.com/v1}"
MODEL="${GPT_IMAGE_MODEL:-gpt-image-2}"
SIZE="${GPT_IMAGE_SIZE:-1024x1536}"
BOOK_DIR="${BOOK_DIR:?请先 export BOOK_DIR=./covers/<书名>}"
REF_IMAGE="${REF_IMAGE:?请先 export REF_IMAGE=本地路径或 URL}"
mkdir -p "$BOOK_DIR/封面"
# 自增版本号
i=1
while [ -f "$BOOK_DIR/封面/封面_v${i}.png" ]; do i=$((i+1)); done
OUT="$BOOK_DIR/封面/封面_v${i}.png"
RESP=$(mktemp)
REF_TMP=""
trap '[ -n "$REF_TMP" ] && rm -f "$REF_TMP"; rm -f "$RESP"' EXIT
# URL 先下载到临时文件,本地路径直接用。用裸 mktemp 以保证 macOS/Linux 行为一致。
case "$REF_IMAGE" in
http://*|https://*)
REF_TMP=$(mktemp)
curl -fsSL --max-time 60 -o "$REF_TMP" "$REF_IMAGE"
REF_LOCAL="$REF_TMP"
;;
*)
[ -f "$REF_IMAGE" ] || { echo "参考图不存在: $REF_IMAGE" >&2; exit 1; }
REF_LOCAL="$REF_IMAGE"
;;
esac
curl -fsS --max-time 240 --retry 2 --retry-delay 5 \
"$BASE_URL/images/edits" \
-H "Authorization: Bearer $GPT_IMAGE_API_KEY" \
--form-string "model=$MODEL" \
--form-string "size=$SIZE" \
--form-string "prompt=$PROMPT" \
-F "image=@$REF_LOCAL" > "$RESP"
if jq -e '.error' "$RESP" >/dev/null 2>&1; then
echo "API error:" >&2
jq '.error' "$RESP" >&2
exit 1
fi
# `// empty` 让缺失字段输出空串而非 "null",配合 -s 检查避免写出 3 字节假 PNG
jq -er '.data[0].b64_json // empty' "$RESP" | base64 --decode > "$OUT"
[ -s "$OUT" ] || { echo "empty or malformed output: $OUT" >&2; head -c 300 "$RESP" >&2; exit 1; }
printf '%s\n' "$PROMPT" > "${OUT%.png}.prompt.txt"
printf '%s\n' "$REF_IMAGE" > "${OUT%.png}.ref.txt"
file "$OUT"
ls -lt "$BOOK_DIR/封面/"
Step 5: Export at platform upload size (when the platform has fixed pixels)
When the platform has fixed upload pixels (Tomato 600×800), crop the original imagecenter-crop + scaleto the exact size, keep the image aspect ratio, keep the original image, and save another _上传 version.SRC Use the original image's absolute path from Step 4,TARGET and use the upload size from Step 1, without relying on temporary variables from the previous shell section:
SRC='<Step 4 生成的原图绝对路径>'
TARGET='<Step 1 确定的平台上传尺寸;无则留空>'
[ -f "$SRC" ] || { echo "封面原图不存在: $SRC" >&2; exit 1; }
if [ -n "$TARGET" ] && [ -f "$SRC" ]; then
UP="${SRC%.png}_上传.png"; W="${TARGET%x*}"; H="${TARGET#*x}"
if command -v magick >/dev/null 2>&1; then M=magick
elif command -v convert >/dev/null 2>&1; then M=convert; else M=""; fi
if [ -n "$M" ]; then
"$M" "$SRC" -resize "${W}x${H}^" -gravity center -extent "${W}x${H}" "$UP" # 缩放填满后居中裁
elif command -v sips >/dev/null 2>&1; then
cp "$SRC" "$UP"
sw=$(sips -g pixelWidth "$UP" | awk '/pixelWidth/{print $NF}')
sh=$(sips -g pixelHeight "$UP" | awk '/pixelHeight/{print $NF}')
if [ $((sw*H)) -ge $((sh*W)) ]; then sips --resampleHeight "$H" "$UP" >/dev/null
else sips --resampleWidth "$W" "$UP" >/dev/null; fi
sips -c "$H" "$W" "$UP" >/dev/null # sips -c 是 高 宽,居中裁
else
echo "无 magick/convert/sips,跳过;手动把 $SRC 居中裁剪+缩放到 $TARGET 再上传" >&2
fi
[ -f "$UP" ] && file "$UP"
fi
The central safe area in the prompt is used to reduce cropping risk; after export, still check according to Step 6 whether the book title and pen name are complete.
Step 6: Quality check + iteration
| Check item | Standard |
|---|---|
| Text rendering | The book title and pen name are clearly legible, and the font style matches the subject matter |
| Subject matter match | The visual style is consistent with the book title's subject matter |
| Reasonable composition | The subject is prominent, and text does not obscure the core image |
| Platform fit | Matches the cover style and tone of the target platform |
| Platform size | The aspect ratio is consistent with the platform; after scaling to the upload size, the book title and pen name are fully visible and not cropped |
If it does not meet the standard or the author wants adjustments, the composition, color tone, font, or platform style can be changed.
Tell the author this at delivery; do not paste commands, environment variables, or API errors to the author, and when it fails, explain the cause and solution in one sentence (e.g., "The image generation API is not configured; you need to set the API Key first"):
封面做好了:`{封面图路径}`{;{平台}上传版({上传尺寸}):`{上传版路径}`}
这版的思路:{构图 + 色调 + 书名字体,一句话}
想调的话可以说:{2-3 个具体方向,如「换成人物特写」「书名改成毛笔字」}
Reference materials
| File | When to load |
|---|---|
| references/cover-styles.md | Subject matter → visual style mapping, platform style details, prompt templates |