How to Generate Consistent Images with GPT-Image2 Templates: A Complete Guide
GPT-Image2 produces reproducible, high-quality images when driven by structured templates that lock in visual style, layout, and aspect ratio while varying only specific content fields.
The freestylefly/awesome-gpt-image-2 repository provides a production-ready framework for eliminating the "random-style" behavior common in AI image generation. By anchoring every generation to predefined templates, you can generate entire series of assets—such as multi-page UI kits or product catalogs—that maintain strict visual consistency across every output.
What Are GPT-Image2 Templates?
A template is a structured prompt that fixes compositional rules including aspect ratio, color palette, typography, and layout primitives while leaving only variable parts (like product names or specific colors) open for modification. The repository ships with 393 cases distilled into 21 industrial-grade templates, documented in docs/templates.md.
Each template ships in two formats:
- Plain-text version – Optimized for direct copy-paste into chat interfaces.
- JSON version – Designed for programmatic consumption via the included skill or custom API calls.
Because the template structure remains immutable across generations, every call using the same template yields images sharing identical aspect ratios (e.g., 9:16 for mobile screenshots), color schemes, and layout primitives (headers, cards, icon placements).
The Generation Pipeline Architecture
When you submit a template to the backend, the system follows a deterministic flow implemented in api/generate-image.js:
UI (React) → /api/generate-image (POST) → reserveGeneration() → Ciyuan API → base64 JPEG → UI
Credit Reservation and Validation
The reserveGeneration() function (or reserveCreditGeneration() for credit-based tiers) records user usage at lines 59-80 of api/generate-image.js, ensuring exactly one credit is consumed per generation. This guarantees resource accountability before any external API call occurs.
Calling the Ciyuan Service
The generateImage() function constructs a request payload specifying model name gpt-image-2 and posts the filled template prompt to https://ciyuan.today/v1/images/generations. The service returns a base64-encoded JPEG string formatted as data:image/jpeg;base64,…, which the frontend in src/main.jsx renders directly without intermediate storage.
Step-by-Step Implementation
Loading and Filling Templates Programmatically
The JSON template catalog lives in data/style-library.json. To generate an image programmatically:
- Load the template matching your use case (e.g.,
type: "UI Screenshot"). - Replace placeholder tokens like
[产品类型]or[颜色]with concrete values. - POST the final prompt string to
/api/generate-image.
// Load template from the style library
import fs from 'fs';
import path from 'path';
const library = JSON.parse(
fs.readFileSync(path.resolve('data/style-library.json'), 'utf8')
);
const uiTemplate = library.find(t => t.type === 'UI Screenshot');
// Inject variables into the template structure
const filled = {
...uiTemplate,
platform: 'Android',
product: 'Fitness Tracker',
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'
};
// Convert to API-ready prompt format
const prompt = `Generate a UI screenshot with the following JSON:\n${JSON.stringify(filled, null, 2)}`;
// Request generation
const response = await fetch('https://your-deployment.com/api/generate-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, caseId: 0 })
});
const result = await response.json();
console.log(result.image); // data:image/jpeg;base64,...
Using the Claude-Code Skill
For rapid prototyping without writing JavaScript, invoke the published NPM package gpt-image-2-style-library built by scripts/generate-style-skill.mjs:
npx gpt-image-2-style-library \
--template UI_Screenshot \
--field platform=Web \
--field product="Travel Planner" \
--field primary_color="#ff6600" \
--field typography="Elegant serif"
The skill automatically constructs the JSON prompt, calls /api/generate-image, and streams the resulting image URL back to the agent.
React Frontend Integration
The src/main.jsx component demonstrates browser-side generation:
import { useState } from 'react';
function GenerateFromTemplate({ templateId }) {
const [imgSrc, setImgSrc] = useState(null);
const [loading, setLoading] = useState(false);
async function generate() {
setLoading(true);
const res = await fetch('/api/generate-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt: `Use the UI Screenshot template with product "Smart Home Hub" and primary_color "#0055ff".`,
caseId: templateId
})
});
const data = await res.json();
if (data.ok) setImgSrc(data.image);
setLoading(false);
}
return (
<>
<button onClick={generate} disabled={loading}>
{loading ? 'Generating…' : 'Generate Image'}
</button>
{imgSrc && <img src={imgSrc} alt="Generated" />}
</>
);
}
Key Files for Template Management
docs/templates.md– Master documentation for all 21 industrial-grade templates including plain-text variants and pitfall-avoidance guidelines.api/generate-image.js– Backend handler implementing credit reservation and Ciyuan API proxying.data/style-library.json– Machine-readable catalog of JSON templates consumed by the skill and programmatic integrations.src/main.jsx– React frontend providing UI for template selection and image display.scripts/generate-style-skill.mjs– Build script publishing the NPM skill for agent-based workflows.
Summary
- Templates eliminate style drift by freezing aspect ratios, color palettes, and layout primitives while varying only content fields.
- The repository provides 21 industrial-grade templates available in both plain-text and JSON formats via
docs/templates.mdanddata/style-library.json. - The generation pipeline relies on
reserveGeneration()inapi/generate-image.jsto ensure credit accountability before calling thegpt-image-2model through the Ciyuan service. - Three integration methods exist: direct Node.js scripting, Claude-Code skill invocation via
npx, and React frontend components.
Frequently Asked Questions
How do I ensure all images in a series use the exact same color palette?
Lock the style object in your JSON template. Specify exact values for primary_color, theme, and typography rather than using descriptive adjectives. Because the template structure remains constant across API calls to /api/generate-image, the model receives identical styling constraints every time, ensuring chromatic consistency across your asset series.
What is the difference between the plain-text and JSON template versions?
The plain-text version is optimized for human readability and direct pasting into chat interfaces, while the JSON version provides machine-readable schema used by the gpt-image-2-style-library skill and programmatic scripts. Both contain identical compositional rules, but JSON enables automated variable injection via property assignment before posting to the generation endpoint.
Where are user credits managed in the codebase?
Credit reservation logic resides in api/generate-image.js at lines 59-80. The reserveGeneration() function checks available credits before proceeding to generateImage(), ensuring users cannot exceed their allocation when calling the Ciyuan image service at https://ciyuan.today/v1/images/generations.
Can I modify the aspect ratio for specific templates?
Yes. Include an explicit constraints field in your template payload specifying the desired ratio (e.g., 9:16 for mobile or 16:9 for desktop). The repository's templates use this field to enforce consistent dimensions across all generations using that template ID, independent of the variable content injected into other fields.
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 →