How to Generate UI Screenshots Using GPT-Image2 Templates: A Complete Developer Guide
You can generate high-fidelity UI screenshots by posting a structured JSON or plain-text template to the /api/generate-image endpoint, which processes the prompt through the Ciyuan API and returns a base64-encoded JPEG image.
The freestylefly/awesome-gpt-image-2 repository provides a production-ready workflow for converting structured UI prompts into screenshot assets using the GPT-Image2 model. This system layers reusable templates, a Vercel-based API handler, and an optional agent skill to automate the creation of consistent, platform-specific interface mockups. By implementing the generation flow documented in api/generate-image.js, you can programmatically produce UI visuals while tracking credit consumption through Supabase reservations.
Understanding the GPT-Image2 UI Template Structure
GPT-Image2 accepts UI screenshot requests in two distinct formats defined in docs/templates.md#tpl-ui. Both formats require you to specify the product type, target platform, layout preferences, visual styling, and output constraints.
Plain-Text Template Format
The plain-text version offers a copy-and-paste approach for manual generation. Use this format when crafting one-off prompts or testing layouts:
为[产品类型]生成一张[平台,如 iOS/Android/Web]界面图。
核心功能:[功能点A]、[功能点B]、[功能点C]。
视觉风格:[极简/科技/拟物],主色[颜色],强调色[颜色]。
布局:[顶部导航/双栏/卡片流],信息层级清晰,留白充足。
输出:高保真UI截图,文字清晰可读,比例[9:16/16:9]。
JSON Template Schema (Preferred for Agents)
For programmatic use, the JSON schema enables the GPT‑Image2 style‑library agent skill (agents/skills/gpt-image-2-style-library) to auto-fill variables and enforce platform constraints. This format guarantees adherence to "avoid-pitfalls" rules such as locked platforms and readable text requirements:
{
"type": "UI Screenshot",
"platform": "iOS",
"product": "Fitness App",
"layout": "Card‑based feed with bottom tab bar",
"style": {
"theme": "Dark Mode",
"primary_color": "Neon Green",
"typography": "Clean sans‑serif"
},
"content": {
"header": "Today's Activity",
"cards": [
{"title": "Running", "data": "5.2 km", "button": "Start"},
{"title": "Calories", "data": "340 kcal"}
]
},
"constraints": "High fidelity, readable text, 9:16 aspect ratio"
}
Backend Generation Flow in api/generate-image.js
When your client POSTs to /api/generate-image, the Vercel handler orchestrates a four-step process defined in api/generate-image.js. The core functions handler, generateImage, reserveGeneration, and completeReservation manage the entire lifecycle:
-
Request validation – The handler verifies the method is
POST, confirms the prompt length does not exceed 6000 characters, and validates thatcaseIdis a valid integer. -
Credit reservation – The system calls the Supabase RPC
reserve_generation_usage(or thereserveCreditGeneration"force credit" variant for super-admins) to create a reservation record and deduct credits. -
Upstream generation – The
generateImagefunction sends a POST request tohttps://ciyuan.today/v1/images/generations(configurable viaCIYUAN_BASE_URL), passing the model namegpt-image-2and your finalized UI prompt. -
Response handling – On success, the API returns a base64 JPEG string (
data:image/jpeg;base64,…) and marks the reservation complete viacompleteReservation. On failure,releaseReservationcancels the hold with error codesUPSTREAM_BUSYorGENERATION_FAILED.
Frontend Integration Example
To generate screenshots from a web client, stringify your JSON template and POST it with a caseId. The following JavaScript example demonstrates building a UI prompt, calling the generation endpoint, and rendering the resulting image:
// Build the structured UI prompt
const uiPrompt = {
type: "UI Screenshot",
platform: "Web",
product: "Task Manager",
layout: "Sidebar navigation + main dashboard",
style: {
theme: "Light",
primary_color: "#0066ff",
typography: "Roboto"
},
content: {
header: "Today's Tasks",
cards: [
{ title: "Design mockups", data: "3 pending", button: "Open" },
{ title: "Code review", data: "1 overdue", button: "Start" }
]
},
constraints: "High fidelity, readable text, 16:9"
};
// POST to the generation endpoint
async function generateUiScreenshot(caseId) {
const resp = await fetch('/api/generate-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt: JSON.stringify(uiPrompt), // API expects a stringified payload
caseId: caseId // Links generation to a gallery case
})
});
const data = await resp.json();
if (!data.ok) throw new Error(data.error);
// Render the base64 image
const img = document.createElement('img');
img.src = data.image; // `data:image/jpeg;base64,…`
document.body.appendChild(img);
}
// Execute with any valid caseId (the repo includes 544 demo cases)
generateUiScreenshot(2).catch(console.error);
Important: Users must be authenticated or the request must originate from a trusted server; otherwise, the handler returns AUTH_REQUIRED. Any integer value works for caseId, which links the generation to specific gallery entries listed in docs/gallery.md.
Automating Prompts with the Style Library Agent
For LLM-driven workflows, install the GPT‑Image2 style‑library skill to generate template JSON from natural language descriptions:
npm install -g gpt-image-2-style-library
gpt-image-2-style-library install all
Invoke the skill from your agent:
Use gpt-image-2-style-library to create a UI screenshot prompt for a "Crypto Dashboard" on Android, dark theme, primary color #00ff99.
The skill outputs a JSON payload matching the schema above, pulling style definitions from data/style-library.json. This eliminates manual template construction and ensures consistent formatting across projects. Refer to agents/skills/gpt-image-2-style-library/SKILL.md for advanced configuration options.
Summary
- Template options – Use the plain-text template from
docs/templates.mdfor manual drafting, or the JSON schema for agent-driven generation viaagents/skills/gpt-image-2-style-library. - API endpoint – POST to
/api/generate-imagewith a stringifiedpromptand integercaseIdto trigger the generation pipeline. - Backend flow – The handler in
api/generate-image.jsvalidates requests, reserves credits via Supabase RPC, calls the Ciyuan endpoint, and returns a base64 JPEG. - Authentication – Requests require valid authentication unless made from trusted server contexts to avoid
AUTH_REQUIREDerrors.
Frequently Asked Questions
What is the maximum prompt length for GPT-Image2 UI templates?
The validator in api/generate-image.js enforces a hard limit of 6000 characters for the prompt string. Exceeding this length causes the handler to reject the request before credit reservation occurs.
How does the credit reservation system work?
The backend uses Supabase RPC functions reserve_generation_usage and reserveCreditGeneration to create a reservation record before calling the upstream Ciyuan API. If generation succeeds, completeReservation finalizes the transaction; if it fails, releaseReservation refunds the credits with error codes like UPSTREAM_BUSY or GENERATION_FAILED.
Can I use plain text instead of JSON for UI screenshot generation?
Yes. The system accepts both formats. Plain text works for manual testing, but JSON is recommended for production use because it integrates with the style-library agent skill and enforces schema validation rules that prevent common prompt pitfalls.
What image format does the GPT-Image2 API return?
The Ciyuan endpoint returns a base64-encoded JPEG string formatted as data:image/jpeg;base64,…. You can embed this directly into HTML image tags or decode it to save as a binary file on your server.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →