GPT Image API
GPT Image API Complete Reference¶
This section provides comprehensive examples for all GPT Image API endpoints available in Vision Studio, including image generation, editing, and inpainting capabilities.
Prerequisites¶
import requests
import json
import base64
# Your API endpoint and key
API_URL = "http://localhost:8527/api/v1/openai"
API_KEY = "your-api-key"
headers = {
"X-API-Key": API_KEY,
"Content-Type": "application/json"
}
Image Generation¶
Generate Images¶
Create high-quality images from text descriptions using GPT's latest image generation capabilities.
Basic Image Generation¶
data = {
"prompt": "A peaceful mountain landscape with a crystal clear lake reflecting snow-capped peaks during golden hour",
"number_of_images": 1,
"aspect_ratio": "1:1",
"quality": "auto",
"background": "auto"
}
response = requests.post(
f"{API_URL}/image/generation/generate-image",
headers=headers,
json=data
)
High-Quality Portrait Generation¶
data = {
"prompt": "Professional headshot of a confident businesswoman in modern office setting, natural lighting, sharp focus",
"number_of_images": 1,
"aspect_ratio": "2:3",
"quality": "high",
"background": "auto"
}
response = requests.post(
f"{API_URL}/image/generation/generate-image",
headers=headers,
json=data
)
Multiple Landscape Images¶
data = {
"prompt": "Vibrant sunset over rolling hills with wildflowers in the foreground, cinematic composition",
"number_of_images": 4,
"aspect_ratio": "3:2",
"quality": "medium",
"background": "auto"
}
response = requests.post(
f"{API_URL}/image/generation/generate-image",
headers=headers,
json=data
)
Transparent Background Generation¶
data = {
"prompt": "A cute cartoon cat sitting upright, simple and clean design suitable for logo use",
"number_of_images": 1,
"aspect_ratio": "1:1",
"quality": "high",
"background": "transparent"
}
response = requests.post(
f"{API_URL}/image/generation/generate-image",
headers=headers,
json=data
)
Creative Art Generation¶
data = {
"prompt": "Abstract digital artwork with flowing colors, geometric patterns, and dynamic energy, modern art style",
"number_of_images": 3,
"aspect_ratio": "1:1",
"quality": "high",
"background": "auto"
}
response = requests.post(
f"{API_URL}/image/generation/generate-image",
headers=headers,
json=data
)
Image Editing¶
Edit Existing Images¶
Transform existing images by providing new descriptions and modifications.
Basic Image Editing¶
data = {
"prompt": "Transform this image to have a warm sunset lighting with golden tones",
"image_url": "https://images.pexels.com/photos/1366919/pexels-photo-1366919.jpeg",
"number_of_images": 1,
"aspect_ratio": "1:1"
}
response = requests.post(
f"{API_URL}/image/editing/edit-image",
headers=headers,
json=data
)
Style Transformation¶
data = {
"prompt": "Convert this photograph into a watercolor painting style with soft brush strokes and artistic flair",
"image_url": "https://images.pexels.com/photos/1391498/pexels-photo-1391498.jpeg",
"number_of_images": 2,
"aspect_ratio": "3:2"
}
response = requests.post(
f"{API_URL}/image/editing/edit-image",
headers=headers,
json=data
)
Mood and Atmosphere Changes¶
data = {
"prompt": "Change the mood to create a mysterious, foggy atmosphere with dramatic lighting and darker tones",
"image_url": "https://images.pexels.com/photos/458976/pexels-photo-458976.jpeg",
"number_of_images": 1,
"aspect_ratio": "2:3"
}
response = requests.post(
f"{API_URL}/image/editing/edit-image",
headers=headers,
json=data
)
Color Enhancement¶
data = {
"prompt": "Enhance the colors to be more vibrant and saturated, increase contrast for a more dynamic look",
"image_url": "https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg",
"number_of_images": 1,
"aspect_ratio": "1:1"
}
Inpainting¶
Manual Mask Inpainting¶
Edit specific areas of images using custom masks to define exactly what should be changed.
Basic Manual Mask Inpainting¶
data = {
"prompt": "Beautiful flowers in the garden",
"image_url": "https://images.pexels.com/photos/29023629/pexels-photo-29023629.jpeg",
"mask_url": "https://example.com/mask.png",
"inpaint_border_only": False
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Object Replacement with Mask¶
data = {
"prompt": "A modern sports car parked in the same location",
"image_url": "https://example.com/street_scene.jpg",
"mask_url": "https://example.com/car_mask.png",
"inpaint_border_only": False
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Background Modification with Mask¶
data = {
"prompt": "Replace the background with a tropical beach scene with palm trees and blue ocean",
"image_url": "https://example.com/portrait.jpg",
"mask_url": "https://example.com/background_mask.png",
"inpaint_border_only": False
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Using Base64 Encoded Images¶
# Function to encode image to base64
def encode_image_to_base64(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# Using base64 encoded files instead of URLs
data = {
"prompt": "Add colorful butterflies flying around the flowers",
"image_file": encode_image_to_base64("path/to/garden.jpg"),
"mask_file": encode_image_to_base64("path/to/mask.png"),
"inpaint_border_only": False
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Border-Only Inpainting¶
Automatically expand images by inpainting only the border areas without requiring custom masks.
Basic Border Expansion¶
data = {
"prompt": "Expand with forest environment",
"image_url": "https://images.pexels.com/photos/29023629/pexels-photo-29023629.jpeg",
"inpaint_border_only": True,
"border_percentage": 0.2
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Minimal Border Expansion¶
data = {
"prompt": "Seamlessly extend the existing scenery",
"image_url": "https://example.com/landscape.jpg",
"inpaint_border_only": True,
"border_percentage": 0.05 # Small 5% border expansion
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Dramatic Border Expansion¶
data = {
"prompt": "Extend into a vast cosmic space with stars and nebulae",
"image_url": "https://example.com/space_scene.jpg",
"inpaint_border_only": True,
"border_percentage": 0.4 # Large 40% border expansion
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Architectural Border Extension¶
data = {
"prompt": "Continue the architectural elements and urban environment",
"image_url": "https://example.com/building.jpg",
"inpaint_border_only": True,
"border_percentage": 0.25
}
response = requests.post(
f"{API_URL}/image/editing/inpaint",
headers=headers,
json=data
)
Advanced Example: Concurrent Image Generation¶
Here's an example of generating multiple images concurrently using asyncio and aiohttp:
import asyncio
import aiohttp
import time
from typing import List, Dict, Any
async def generate_image_async(session: aiohttp.ClientSession, prompt: str,
aspect_ratio: str = "1:1", quality: str = "auto",
number_of_images: int = 1, request_id: int = 0) -> Dict[str, Any]:
"""Generate a single image asynchronously."""
url = f"{API_URL}/image/generation/generate-image"
data = {
"prompt": prompt,
"number_of_images": number_of_images,
"aspect_ratio": aspect_ratio,
"quality": quality,
"background": "auto"
}
headers_async = {
"X-API-Key": API_KEY,
"Content-Type": "application/json"
}
start_time = time.time()
try:
async with session.post(url, headers=headers_async, json=data) as response:
result = await response.json()
duration = time.time() - start_time
return {
"request_id": request_id,
"prompt": prompt,
"aspect_ratio": aspect_ratio,
"quality": quality,
"number_of_images": number_of_images,
"status": response.status,
"duration": duration,
"result": result
}
except Exception as e:
return {
"request_id": request_id,
"prompt": prompt,
"aspect_ratio": aspect_ratio,
"quality": quality,
"number_of_images": number_of_images,
"status": -1,
"duration": time.time() - start_time,
"error": str(e)
}
async def process_images_concurrently():
"""Generate multiple images with different settings concurrently."""
# Test prompts with different styles and requirements
test_prompts = [
{
"prompt": "A majestic mountain landscape with crystal clear lake",
"aspect_ratio": "3:2",
"quality": "high",
"number_of_images": 1
},
{
"prompt": "Professional headshot of a confident businessperson",
"aspect_ratio": "2:3",
"quality": "high",
"number_of_images": 2
},
{
"prompt": "Abstract digital art with vibrant colors and geometric shapes",
"aspect_ratio": "1:1",
"quality": "medium",
"number_of_images": 3
},
{
"prompt": "Cozy coffee shop interior with warm lighting",
"aspect_ratio": "3:2",
"quality": "auto",
"number_of_images": 1
},
{
"prompt": "Futuristic city skyline at sunset with flying cars",
"aspect_ratio": "3:2",
"quality": "high",
"number_of_images": 1
},
{
"prompt": "Cute cartoon mascot character for a tech company",
"aspect_ratio": "1:1",
"quality": "high",
"number_of_images": 4
},
{
"prompt": "Elegant product photography of luxury watch",
"aspect_ratio": "1:1",
"quality": "high",
"number_of_images": 1
},
{
"prompt": "Fantasy landscape with magical forest and glowing creatures",
"aspect_ratio": "2:3",
"quality": "medium",
"number_of_images": 2
}
]
# Configure session for concurrent requests
timeout = aiohttp.ClientTimeout(total=180) # 3 minute timeout
connector = aiohttp.TCPConnector(limit=10)
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
tasks = []
total_expected_images = 0
# Create tasks for all prompts
for i, prompt_config in enumerate(test_prompts):
task = generate_image_async(
session=session,
prompt=prompt_config["prompt"],
aspect_ratio=prompt_config["aspect_ratio"],
quality=prompt_config["quality"],
number_of_images=prompt_config["number_of_images"],
request_id=i
)
tasks.append(task)
total_expected_images += prompt_config["number_of_images"]
print(f"Starting {len(tasks)} concurrent image generation requests...")
print(f"Expected total images: {total_expected_images}")
start_time = time.time()
# Execute all requests concurrently
results = await asyncio.gather(*tasks)
total_time = time.time() - start_time
print(f"Completed all requests in {total_time:.3f} seconds")
# Process and display results
successful_requests = 0
failed_requests = 0
total_images_generated = 0
results_by_quality = {"high": [], "medium": [], "auto": []}
results_by_aspect_ratio = {}
for result in results:
if result["status"] == 200 and result["result"]["success"]:
successful_requests += 1
images = result["result"]["data"]["images"]
total_images_generated += len(images)
quality = result["quality"]
aspect_ratio = result["aspect_ratio"]
# Group by quality
results_by_quality[quality].append({
"prompt": result["prompt"],
"images": images,
"duration": result["duration"],
"aspect_ratio": aspect_ratio
})
# Group by aspect ratio
if aspect_ratio not in results_by_aspect_ratio:
results_by_aspect_ratio[aspect_ratio] = []
results_by_aspect_ratio[aspect_ratio].append({
"prompt": result["prompt"],
"images": images,
"quality": quality,
"duration": result["duration"]
})
print(f"✅ Request {result['request_id']}: {quality} quality, {aspect_ratio} ratio - {len(images)} images in {result['duration']:.3f}s")
for j, image in enumerate(images):
print(f" Image {j+1}: {image['url']}")
else:
failed_requests += 1
error_msg = result.get('error', result.get('result', {}).get('message', f"HTTP {result['status']}"))
print(f"❌ Request {result['request_id']}: {result['prompt'][:50]}... - {error_msg}")
print(f"\n📊 Summary:")
print(f" Total requests: {len(tasks)}")
print(f" Successful requests: {successful_requests}")
print(f" Failed requests: {failed_requests}")
print(f" Total images generated: {total_images_generated}")
print(f" Expected images: {total_expected_images}")
print(f" Total time: {total_time:.3f} seconds")
if successful_requests > 0:
avg_duration = sum(r['duration'] for r in results if r['status'] == 200) / successful_requests
print(f" Average request time: {avg_duration:.3f}s")
print(f" Requests per second: {len(results) / total_time:.2f}")
print(f" Images per second: {total_images_generated / total_time:.2f}")
# Display results organized by quality
print("\n" + "="*80)
print("RESULTS BY QUALITY")
print("="*80)
for quality, quality_results in results_by_quality.items():
if quality_results:
print(f"\n{quality.upper()} QUALITY RESULTS:")
print("-" * 40)
for i, res in enumerate(quality_results, 1):
print(f"\n{i}. Prompt ({res['aspect_ratio']}, {res['duration']:.3f}s):")
print(f" {res['prompt']}")
print(f" Generated {len(res['images'])} images:")
for j, image in enumerate(res['images'], 1):
print(f" {j}. {image['url']}")
# Display results organized by aspect ratio
print("\n" + "="*80)
print("RESULTS BY ASPECT RATIO")
print("="*80)
for ratio, ratio_results in results_by_aspect_ratio.items():
if ratio_results:
print(f"\n{ratio} ASPECT RATIO RESULTS:")
print("-" * 40)
for i, res in enumerate(ratio_results, 1):
print(f"\n{i}. {res['quality'].upper()} quality ({res['duration']:.3f}s):")
# Truncate long prompts for better readability
prompt = res['prompt']
if len(prompt) > 80:
prompt = prompt[:77] + "..."
print(f" {prompt}")
print(f" {len(res['images'])} images generated")
# Run the concurrent image generation
if __name__ == "__main__":
asyncio.run(process_images_concurrently())
This concurrent example demonstrates: - Multi-quality testing: Tests high, medium, and auto quality settings - Various aspect ratios: Covers square (1:1), portrait (2:3), and landscape (3:2) formats - Bulk generation: Requests different numbers of images per prompt (1-4 images) - Organized results: Groups results by quality and aspect ratio for analysis - Performance metrics: Tracks total processing time, images per second, and success rates - Error handling: Robust error handling for network issues and API errors - Detailed logging: Shows progress for each request with timing information
Available Endpoints Summary¶
| Endpoint | Description | Parameters | Output |
|---|---|---|---|
/image/generation/generate-image |
Generate images from text | prompt, number_of_images, aspect_ratio, quality, background |
Generated image URLs |
/image/editing/edit-image |
Edit existing images | prompt, image_url, number_of_images, aspect_ratio |
Edited image URLs |
/image/editing/inpaint |
Inpaint with masks or borders | prompt, image_url/file, mask_url/file, inpaint_border_only, border_percentage |
Inpainted image URLs |
Parameter Details¶
Aspect Ratios¶
1:1- Square format (1024×1024)2:3- Portrait format (683×1024)3:2- Landscape format (1024×683)
Quality Settings¶
auto- Automatic quality selection based on contentmedium- Balanced quality and speedhigh- Maximum quality (slower generation)
Background Options¶
auto- Automatic background handlingtransparent- Generate with transparent background (PNG)
Border Percentage Range¶
0.01to0.5(1% to 50% of image dimensions)
Best Practices¶
- Prompt clarity: Use descriptive, specific prompts for better results
- Quality selection: Use
highfor final images,mediumfor iterations - Aspect ratio choice: Select ratios based on intended use (portraits vs landscapes)
- Batch processing: Use concurrent requests for multiple images
- Error handling: Implement retry logic for network failures
- Mask quality: Ensure masks are clear with well-defined boundaries
- Border inpainting: Start with smaller percentages (5-20%) for natural extensions
- Resource management: Monitor processing times as high-quality images take longer