Achieving High-Fidelity UI Screenshots for iOS and Android with GPT-Image2
GPT-Image2 provides a production-ready pipeline that converts detailed textual prompts into photorealistic mobile UI screenshots through a Vite React frontend, Vercel serverless API gateway, and external CIYUAN generation service.
The freestylefly/awesome-gpt-image-2 repository offers a complete full-stack implementation for generating iOS and Android UI screenshots that closely mimic real device captures. This open-source project combines Supabase authentication, credit-based rate limiting, and the GPT-Image2 model to deliver consistent, high-quality results suitable for mockups, presentations, and design validation.
Architecture Overview
The system operates across three distinct layers that handle prompt ingestion, credit management, and actual image synthesis.
Frontend: Vite-Powered React Application
The client layer in src/main.jsx manages user sessions, prompt input, and image display. It communicates with the backend via authenticated POST requests.
API Gateway: Vercel Serverless Functions
The api/generate-image.js file implements four critical responsibilities:
- Session verification via Supabase JWT validation
- Credit reservation through
reserveGenerationorreserveCreditGenerationstored procedures - Upstream forwarding to the CIYUAN endpoint
- Transaction settlement with
completeReservationorreleaseReservationrollback on failure
Generation Service: CIYUAN External API
The actual inference occurs at https://ciyuan.today/v1/images/generations, running GPT-Image2 on GPU clusters and returning Base64-encoded JPEG data.
How the UI Screenshot Pipeline Works
Understanding the request flow explains why this system achieves reliable high-fidelity output.
1. Authentication and Session Validation
Users authenticate through Supabase Auth, obtaining a JWT stored client-side. Every generation request includes this token in the Authorization header. The backend validates the session before processing.
2. Credit Reservation System
Before any upstream call, the system reserves one generation credit:
reserve_generation_usagestored procedure locks the credit and returns current balance- The reservation object tracks
reservation_id,user_id, andcase_id - Credits are only deducted permanently after successful image retrieval
This prevents wastage from failed upstream requests or network timeouts.
3. Prompt Validation
The API enforces three constraints:
- Prompt must be non-empty
- Length must not exceed
MAX_PROMPT_LENGTH(6,000 characters) caseIdmust be a valid number referencingdata/cases.json
4. Image Generation Request
The generateImage function constructs a POST payload with these parameters:
| Parameter | Value | Purpose |
|---|---|---|
model |
'gpt-image-2' |
Specifies the inference model |
prompt |
User text | Describes UI elements, device, lighting |
n |
1 |
Single image output |
size |
'1024x1024' |
Square aspect ratio suitable for mobile |
quality |
'low' |
JPEG compression for faster transfer |
The CIYUAN response contains b64_json, which the API transforms into a data URL: data:image/jpeg;base64,…
5. Reservation Finalization
- Success path:
completeReservationmarks usage as consumed - Failure path:
releaseReservationrolls back with error codes (GENERATION_FAILEDorUPSTREAM_BUSY)
6. Client Response
The API returns a normalized object:
{
"ok": true,
"image": "data:image/jpeg;base64,/9j/4AAQ...",
"user": {
"credits_remaining": 47,
"generation_count": 23,
"reservation_id": "uuid-v4-string"
}
}
Crafting Effective UI Screenshot Prompts
The data/cases.json file contains 544 pre-validated prompt templates. For mobile UI screenshots, case 330 ("Moonlit livestream scene") demonstrates optimal prompt structure:
A high-fidelity iOS/Android livestream screenshot, 21:9 aspect ratio,
dark UI theme, chat message overlay with timestamps, viewer count 99,996,
popularity rating 18+, "airplane" gift animation flying across screen,
soft side lighting from left, realistic phone screen glare,
iPhone 15 Pro front selfie camera perspective, shallow depth of field
Key prompt ingredients for high-fidelity UI screenshots:
- Device specification – "iPhone 15 Pro", "Samsung Galaxy S24 Ultra", "Pixel 8"
- Aspect ratio – "21:9", "19.5:9", "20:9" for modern devices
- UI element enumeration – "status bar", "notch", "bottom navigation", "floating action button"
- Environmental context – "screen glare", "finger smudges", "ambient reflection"
- Camera parameters – "24mm lens", "f/1.8", "shallow depth of field"
Implementation Examples
Browser-Based Request (React)
async function generateUIScreenshot(prompt, caseId = 330) {
const response = await fetch('/api/generate-image', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${supabaseSession.access_token}`
},
body: JSON.stringify({ prompt, caseId })
});
const data = await response.json();
if (data.ok) {
return {
imageUrl: data.image,
creditsRemaining: data.user.credits_remaining
};
}
throw new Error(data.error || 'Generation failed');
}
Server-Side Integration (Node.js)
import fetch from 'node-fetch';
const CIYUAN_API = 'https://ciyuan.today/v1/images/generations';
async function generateDirectScreenshot(prompt) {
const response = await fetch(CIYUAN_API, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.CIYUAN_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-image-2',
prompt,
n: 1,
size: '1024x1024',
quality: 'low'
})
});
const result = await response.json();
return `data:image/jpeg;base64,${result.data[0].b64_json}`;
}
Admin Credit Override
// From api/generate-image.js internals
const reservation = await reserveCreditGeneration(
supabaseClient,
targetUserId,
caseId,
prompt
);
// Allows super-admins to generate even when user credits are depleted
Key Source Files Reference
| File | Responsibility | Direct Link |
|---|---|---|
api/generate-image.js |
Core orchestration: auth, reservation, CIYUAN call, error handling | source |
src/main.jsx |
React entry point: UI rendering, prompt capture, image display | source |
data/cases.json |
Machine-readable catalog of 544 prompt templates with metadata | source |
docs/gallery-part-2.md |
Case 330 documentation with bilingual prompts and examples | source |
agents/skills/gpt-image-2-style-library/SKILL.md |
Agent skill for Claude Code, Codex, Cursor integration | source |
scripts/generate-style-skill.mjs |
Build script that packages style library for agent consumption | source |
Performance and Reliability Characteristics
The pipeline implements several safeguards for production use:
- Idempotent reservations – Duplicate reservation attempts return the same reservation ID
- Automatic rollback – Failed generations release credits within 30 seconds
- Upstream circuit breaking –
UPSTREAM_BUSYerror triggers client-side retry with exponential backoff - JPEG low quality – Reduces payload size ~75% versus PNG with minimal perceptual loss for UI screenshots
Summary
- GPT-Image2 generates photorealistic iOS and Android UI screenshots from structured text prompts
- The three-layer architecture (React frontend, Vercel API, CIYUAN service) separates concerns and enables scaling
- Credit reservation system prevents resource wastage and enables accurate usage tracking
- Case 330 in
data/cases.jsonprovides a proven template for livestream-style mobile UI screenshots - Base64 JPEG output integrates directly into HTML
<img>tags without secondary storage
Frequently Asked Questions
What makes GPT-Image2 suitable for UI screenshot generation?
GPT-Image2 is specifically trained on paired UI designs and device photography, allowing it to render believable screen glare, bezel shadows, and interface element spacing. The model understands aspect ratios, safe areas, and platform-specific design patterns (iOS Human Interface Guidelines vs. Material Design) when these are specified in the prompt.
Can I use this without the credit system for internal tools?
Yes. The reserveGeneration function checks user tier; super-admins can call reserveCreditGeneration to bypass balance validation. For completely open internal deployments, you could modify api/generate-image.js to skip reservation entirely and call the CIYUAN endpoint directly, though this removes usage tracking and abuse protection.
How do I add custom device templates beyond the 544 cases?
Create new entries in data/cases.json with a unique id, bilingual prompt objects, and metadata fields. Run npm run generate-style-skill to rebuild agents/skills/gpt-image-2-style-library/SKILL.md. The new case becomes available immediately to the API—no redeployment required since cases.json is read at request time.
What resolution should I request for App Store screenshots?
Request 1024x1024 from the API, then post-process to required dimensions. App Store Connect requires:
- 6.7" iPhone: 1290 x 2796 pixels
- 6.5" iPhone: 1284 x 2778 pixels
- 5.5" iPhone: 1242 x 2208 pixels
Upscale with Lanczos resampling and add device frames using tools like fastlane frameit or Figma templates for final submission assets.
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 →