Images API
Image generation API usage guide with multi-language examples
Images API
The Images API provides AI image generation capabilities, supporting image creation from text descriptions, image editing, and generating image variations.
Basic Information
API Endpoints
- Image generation:
https://api.routin.ai/v1/images/generations - Image editing:
https://api.routin.ai/v1/images/edits - Image variations:
https://api.routin.ai/v1/images/variations
Authentication Add your API Key in the request header:
Authorization: Bearer YOUR_API_KEYMeteorAI is fully compatible with the OpenAI Images API, supporting DALL·E 3, DALL·E 2, and other image generation models.
1. Image Generation
Generate brand new images from text descriptions.
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | Image description, up to 4000 characters |
model | string | No | Model name, such as dall-e-3, dall-e-2 |
n | integer | No | Number of images to generate (1-10), DALL·E 3 only supports 1 |
size | string | No | Image size, such as 1024x1024, 1792x1024, 1024x1792 |
quality | string | No | Image quality: standard or hd (DALL·E 3 only) |
style | string | No | Style: vivid or natural (DALL·E 3 only) |
response_format | string | No | Return format: url or b64_json |
Response Format
{
"created": 1677652288,
"data": [
{
"url": "https://...",
"revised_prompt": "Optimized prompt"
}
]
}Code Examples
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.routin.ai/v1"
)
response = client.images.generate(
model="dall-e-3",
prompt="一只可爱的橙色小猫在草地上玩耍,水彩画风格",
size="1024x1024",
quality="standard",
n=1
)
image_url = response.data[0].url
print(f"Image URL: {image_url}")
print(f"Revised prompt: {response.data[0].revised_prompt}")import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.routin.ai/v1',
});
async function main() {
const response = await client.images.generate({
model: 'dall-e-3',
prompt: '一只可爱的橙色小猫在草地上玩耍,水彩画风格',
size: '1024x1024',
quality: 'standard',
n: 1,
});
const imageUrl = response.data[0].url;
console.log(`Image URL: ${imageUrl}`);
console.log(`Revised prompt: ${response.data[0].revised_prompt}`);
}
main();const OpenAI = require('openai');
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.routin.ai/v1',
});
client.images.generate({
model: 'dall-e-3',
prompt: '一只可爱的橙色小猫在草地上玩耍,水彩画风格',
size: '1024x1024',
quality: 'standard',
n: 1,
}).then(response => {
const imageUrl = response.data[0].url;
console.log(`Image URL: ${imageUrl}`);
console.log(`Revised prompt: ${response.data[0].revised_prompt}`);
});using OpenAI.Images;
var client = new ImageClient(
model: "dall-e-3",
apiKey: "YOUR_API_KEY",
new OpenAIClientOptions
{
Endpoint = new Uri("https://api.routin.ai/v1")
}
);
var response = await client.GenerateImageAsync(
"一只可爱的橙色小猫在草地上玩耍,水彩画风格",
new ImageGenerationOptions
{
Size = GeneratedImageSize.W1024xH1024,
Quality = GeneratedImageQuality.Standard,
ResponseFormat = GeneratedImageFormat.Uri
}
);
var imageUrl = response.Value.ImageUri;
Console.WriteLine($"Image URL: {imageUrl}");
Console.WriteLine($"Revised prompt: {response.Value.RevisedPrompt}");curl https://api.routin.ai/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "dall-e-3",
"prompt": "一只可爱的橙色小猫在草地上玩耍,水彩画风格",
"size": "1024x1024",
"quality": "standard",
"n": 1
}'Download and Save Image
from openai import OpenAI
import requests
from pathlib import Path
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.routin.ai/v1"
)
response = client.images.generate(
model="dall-e-3",
prompt="未来城市的夜景,赛博朋克风格",
size="1024x1024"
)
# Download image
image_url = response.data[0].url
image_data = requests.get(image_url).content
# Save locally
output_path = Path("generated_image.png")
output_path.write_bytes(image_data)
print(f"Image saved to: {output_path}")import OpenAI from 'openai';
import fs from 'fs';
import https from 'https';
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.routin.ai/v1',
});
async function main() {
const response = await client.images.generate({
model: 'dall-e-3',
prompt: '未来城市的夜景,赛博朋克风格',
size: '1024x1024',
});
const imageUrl = response.data[0].url!;
const file = fs.createWriteStream('generated_image.png');
https.get(imageUrl, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close();
console.log('Image saved to: generated_image.png');
});
});
}
main();using OpenAI.Images;
var client = new ImageClient(
model: "dall-e-3",
apiKey: "YOUR_API_KEY",
new OpenAIClientOptions
{
Endpoint = new Uri("https://api.routin.ai/v1")
}
);
var response = await client.GenerateImageAsync(
"未来城市的夜景,赛博朋克风格",
new ImageGenerationOptions
{
Size = GeneratedImageSize.W1024xH1024
}
);
// Download image
using var httpClient = new HttpClient();
var imageBytes = await httpClient.GetByteArrayAsync(response.Value.ImageUri);
// Save locally
await File.WriteAllBytesAsync("generated_image.png", imageBytes);
Console.WriteLine("Image saved to: generated_image.png");2. Image Editing
Edit specified areas of existing images based on prompts.
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
image | file | Yes | Image file to edit (PNG, < 4MB) |
mask | file | No | Transparent areas indicate parts to edit |
prompt | string | Yes | Edit description |
model | string | No | Model name, default dall-e-2 |
n | integer | No | Number of images to generate (1-10) |
size | string | No | Image size |
Code Examples
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.routin.ai/v1"
)
response = client.images.edit(
model="dall-e-2",
image=open("original.png", "rb"),
mask=open("mask.png", "rb"),
prompt="在透明区域添加一只蝴蝶",
n=1,
size="1024x1024"
)
image_url = response.data[0].url
print(f"Edited image: {image_url}")import OpenAI from 'openai';
import fs from 'fs';
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.routin.ai/v1',
});
async function main() {
const response = await client.images.edit({
model: 'dall-e-2',
image: fs.createReadStream('original.png'),
mask: fs.createReadStream('mask.png'),
prompt: '在透明区域添加一只蝴蝶',
n: 1,
size: '1024x1024',
});
const imageUrl = response.data[0].url;
console.log(`Edited image: ${imageUrl}`);
}
main();using OpenAI.Images;
var client = new ImageClient(
model: "dall-e-2",
apiKey: "YOUR_API_KEY",
new OpenAIClientOptions
{
Endpoint = new Uri("https://api.routin.ai/v1")
}
);
using var imageStream = File.OpenRead("original.png");
using var maskStream = File.OpenRead("mask.png");
var response = await client.GenerateImageEditAsync(
imageStream,
"在透明区域添加一只蝴蝶",
new ImageEditOptions
{
Mask = maskStream,
Size = GeneratedImageSize.W1024xH1024
}
);
var imageUrl = response.Value.ImageUri;
Console.WriteLine($"Edited image: {imageUrl}");curl https://api.routin.ai/v1/images/edits \
-H "Authorization: Bearer YOUR_API_KEY" \
-F image="@original.png" \
-F mask="@mask.png" \
-F prompt="在透明区域添加一只蝴蝶" \
-F model="dall-e-2" \
-F n=1 \
-F size="1024x1024"3. Image Variations
Generate similar variations of the original image.
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
image | file | Yes | Source image file (PNG, < 4MB) |
model | string | No | Model name, default dall-e-2 |
n | integer | No | Number of images to generate (1-10) |
size | string | No | Image size |
Code Examples
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.routin.ai/v1"
)
response = client.images.create_variation(
model="dall-e-2",
image=open("original.png", "rb"),
n=2,
size="1024x1024"
)
for i, image_data in enumerate(response.data):
print(f"Variation {i+1}: {image_data.url}")import OpenAI from 'openai';
import fs from 'fs';
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.routin.ai/v1',
});
async function main() {
const response = await client.images.createVariation({
model: 'dall-e-2',
image: fs.createReadStream('original.png'),
n: 2,
size: '1024x1024',
});
response.data.forEach((imageData, i) => {
console.log(`Variation ${i + 1}: ${imageData.url}`);
});
}
main();using OpenAI.Images;
var client = new ImageClient(
model: "dall-e-2",
apiKey: "YOUR_API_KEY",
new OpenAIClientOptions
{
Endpoint = new Uri("https://api.routin.ai/v1")
}
);
using var imageStream = File.OpenRead("original.png");
var response = await client.GenerateImageVariationsAsync(
imageStream,
2,
new ImageVariationOptions
{
Size = GeneratedImageSize.W1024xH1024
}
);
for (int i = 0; i < response.Value.Count; i++)
{
Console.WriteLine($"Variation {i + 1}: {response.Value[i].ImageUri}");
}curl https://api.routin.ai/v1/images/variations \
-H "Authorization: Bearer YOUR_API_KEY" \
-F image="@original.png" \
-F model="dall-e-2" \
-F n=2 \
-F size="1024x1024"Supported Models
DALL·E 3
- Sizes: 1024x1024, 1792x1024, 1024x1792
- Quality: standard, hd
- Style: vivid, natural
- Features: Higher image quality and detail, supports prompt optimization
DALL·E 2
- Sizes: 256x256, 512x512, 1024x1024
- Features: Supports image editing and variation generation, lower cost
DALL·E 3 only supports generating single images, while DALL·E 2 supports batch generation and image editing features.
Best Practices
1. Write Effective Prompts
# ❌ Poor prompt
prompt = "一只猫"
# ✅ Good prompt
prompt = "一只毛茸茸的橙色波斯猫,坐在天鹅绒沙发上,柔和的自然光线,专业摄影,浅景深"Prompt Elements:
- Subject: Describe the main object to generate
- Details: Color, texture, style
- Environment: Background, scene, lighting
- Art style: Oil painting, watercolor, 3D rendering, etc.
- Perspective: Front view, side view, bird's eye view, etc.
2. Use Negative Prompts (by describing what to avoid)
# Specify unwanted elements in the prompt
prompt = "一个现代化的厨房,干净整洁,没有杂物,没有人物"3. Iterative Refinement
# Generate initial version
response1 = client.images.generate(
model="dall-e-3",
prompt="一座未来城市"
)
# Refine prompt based on results
response2 = client.images.generate(
model="dall-e-3",
prompt="一座未来城市,高耸的摩天大楼,霓虹灯,夜景,雨后湿润的街道,赛博朋克风格"
)4. Cost Optimization
# Use standard quality for development/testing
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
quality="standard" # Lower cost
)
# Use hd for production when high quality is needed
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
quality="hd" # Higher quality, higher cost
)5. Base64 Format for Immediate Display
# Use base64 format to avoid additional network requests
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
response_format="b64_json"
)
import base64
image_data = base64.b64decode(response.data[0].b64_json)
# Use image data directly in applicationUse Cases
- Content Creation: Generate images for blogs and social media
- Product Design: Quickly generate product prototypes and concept art
- Marketing Materials: Create ads, posters, banners
- Game Development: Generate game assets and concept art
- Education: Create teaching illustrations and diagrams
- E-commerce: Generate product scenes and usage scenarios
Error Handling
Image generation may be rejected due to content policy violations. Ensure prompts comply with usage guidelines.
from openai import OpenAI, APIError
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.routin.ai/v1"
)
try:
response = client.images.generate(
model="dall-e-3",
prompt="测试提示词"
)
print(response.data[0].url)
except APIError as e:
if "content_policy_violation" in str(e):
print("Prompt violates content policy, please modify and retry")
else:
print(f"API error: {e}")
except Exception as e:
print(f"Unknown error: {e}")import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.routin.ai/v1',
});
async function main() {
try {
const response = await client.images.generate({
model: 'dall-e-3',
prompt: '测试提示词',
});
console.log(response.data[0].url);
} catch (error: any) {
if (error.code === 'content_policy_violation') {
console.error('Prompt violates content policy, please modify and retry');
} else {
console.error(`Error: ${error.message}`);
}
}
}
main();using OpenAI.Images;
using OpenAI;
var client = new ImageClient(
model: "dall-e-3",
apiKey: "YOUR_API_KEY",
new OpenAIClientOptions
{
Endpoint = new Uri("https://api.routin.ai/v1")
}
);
try
{
var response = await client.GenerateImageAsync("测试提示词");
Console.WriteLine(response.Value.ImageUri);
}
catch (ClientResultException ex) when (ex.Message.Contains("content_policy"))
{
Console.WriteLine("Prompt violates content policy, please modify and retry");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}Common Error Codes
| Error Code | Description | Solution |
|---|---|---|
| 401 | Invalid API Key | Check Authorization header |
| 400 | Invalid request parameters | Check image format, size, and parameters |
| 400 | Content policy violation | Modify prompt to ensure compliance |
| 429 | Rate limit exceeded | Reduce request frequency |
| 500 | Server error | Retry later |
Content Policy
Ensure generated image content complies with the following guidelines:
- No violent, pornographic, hateful, or illegal content
- No infringement of others' copyright, portrait rights, or other rights
- No misleading or false information
- Comply with local laws and regulations
Requests violating content policy will be rejected. Frequent violations may result in API Key suspension.
More Resources
- Chat Completions API - Chat interface
- Embeddings API - Text embeddings interface
- Audio API - Speech recognition and synthesis interface